How do I apply my function in a pipeline.
This is my df
library(tidyverse)
library(lubridate)
status <- c("exit", "start", "start", "exit", "start", "exit", "exit", "suspended", "start")
active_date <- c("1/05/2018", "11/10/2017", "1/05/2018", "1/07/2018", "1/07/2018", "27/09/2018", "27/09/2018", "27/09/2018", "25/10/2018")
start_date <- c("11/10/2017", "11/10/2017", "1/05/2018", "1/05/2018", "1/07/2018", "1/07/2018", "1/07/2018", "27/09/2018", "27/09/2018")
exit_date <- c("1/05/2018", NA, NA, "1/07/2018", NA, "27/09/2018", "27/09/2018", NA, NA)
suspend_start_date <- c(NA, NA, NA, NA, NA, "27/09/2018", "27/09/2018", "27/09/2018", "27/09/2018")
suspend_end_date <- c(NA, NA, NA, NA, NA, NA, "25/10/2018", NA, "25/10/2018")
df <- cbind(status, start_date, exit_date, suspend_start_date, suspend_end_date) %>%
as_tibble %>% mutate_at(2:5, .funs = dmy)
This is my function
find_active_date <- function(x = status,
exit_date,
suspend_start_date,
suspend_end_date,
start_date){
case_when(x == "exit" ~ exit_date,
x == "suspended" ~ suspend_start_date,
x == "start" & !is.na(suspend_end_date) ~ suspend_end_date,
TRUE ~ start_date)
}
The function works when I put in one piece of input at a time like this:
find_active_date(df$status[1],
df$exit_date[1],
df$suspend_start_date[1],
df$suspend_end_date[1],
df$start_date[1])
This is the desired output
output_df <- cbind(df, active_date) %>%
as_tibble %>%
mutate(active_date = dmy(active_date))
This is what I have tried which is not working
df %>%
rowwise %>%
mutate(active_date = find_active_date(status,
suspend_start_date,
suspend_end_date,
start_date))