Home > Blockchain >  Can I use if_else on one column to mutate several other columns?
Can I use if_else on one column to mutate several other columns?

Time:12-24

I have survey data that lists whether an event occurs in one month, or whether it occurs in every month. If a respondent has replied that the event occurs in every month, the individual months are all 0 with a 1 in the same_all_year_round column as below.

> dput(df[1:13])
structure(list(jun = c(0, 0, 1, 0), jul = c(0, 0, 0, 0), aug = c(1, 
0, 0, 0), sep = c(0, 0, 0, 0), oct = c(1, 0, 0, 0), nov = c(0, 
0, 0, 0), dec = c(1, 0, 0, 1), jan = c(0, 0, 0, 0), feb = c(1, 
0, 1, 0), mar = c(0, 0, 1, 0), apr = c(1, 0, 0, 0), may = c(0, 
0, 0, 0), same_all_year_round = c(0, 1, 0, 0)), row.names = c(NA, 
-4L), class = "data.frame")

If a respondent has replied that the event occurs in every month, I would like to populate each individual month column with a 1. As below:

jun <- c(0, 1, 1, 0)
jul <- c(0, 1, 0, 0)
aug <- c(1, 1, 0, 0)
sep <- c(0, 1, 0, 0)
oct <- c(1, 1, 0, 0)
nov <- c(0, 1, 0, 0)
dec <- c(1, 1, 0, 1)
jan <- c(0, 1, 0, 0)
feb <- c(1, 1, 1, 0)
mar <- c(0, 1, 1, 0)
apr <- c(1, 1, 0, 0)
may <- c(0, 1, 0, 0)
same_all_year_round <- c(0, 1, 0, 0)
df <- data.frame(jun, jul, aug, sep, oct, nov, dec, jan, feb, mar, apr, may, same_all_year_round)

I have the following code (that is working) but would prefer to follow the DRY rule. I have just included 3 months for the sake of brevity.

    df <- df %>%
  mutate(jul = if_else(same_all_year_round == 1, 1, 0),
         aug = if_else(same_all_year_round == 1, 1, 0),
         sep = if_else(same_all_year_round == 1, 1, 0))

Should I be using a version of apply? I've tried a couple of different things but can't seem to make anything work.

CodePudding user response:

Your if_else was misformed because in the case where same_all_year_round was not 1, it would set the result to 0, but your sample output showed that you wanted to not modify the result in that case. We can fix it and apply it to all columns with across():

df <- df %>% 
  mutate(across(jul:jun, ~if_else(same_all_year_round == 1, 1, .x)))
  • Related