Suppose I have a data set which looks like:
library(tidyverse)
df_raw <- data.frame(id = paste0('id', sample(c(1:13), replace = TRUE)), startTime = as.Date(rbeta(13, 0.7, 10) * 100, origin = "2016-01-01"), Channel = paste0('c', sample(c(1:3), 13, replace = TRUE, prob = c(0.2, 0.12, 0.3))) ) %>%
group_by(id) %>%
mutate(totals_transactions = sample(c(0, 1), n(), prob = c(0.9, 0.1), replace = TRUE)) %>%
ungroup() %>%
arrange(id, startTime)
Now I would like to summarize the same id's together and add columns to this new dataframe which indicates whether or not a certain channel is used by that id. I have done it like this:
seq_summaries <- df_raw %>%
group_by(id) %>%
summarize(
c1_touches = max(ifelse(Channel == "c1",1,0)),
c2_touches = max(ifelse(Channel == "c2",1,0)),
c3_touches = max(ifelse(Channel == "c3",1,0)),
conversions = sum(totals_transactions)
) %>% ungroup()
However, I'm searching for a way in which I don't have to manually create columns for every channel, as the number of channels could be much more than three which results in a lot of work.
dput(data)rather than code, particularly if you're not using base R. Where doesdmap_atcome from?purrrly, but the OP has removed that line, sopurrrlyis not required now.