Home > Blockchain >  Mutate multiply columns based on conditional and column name
Mutate multiply columns based on conditional and column name

Time:03-18

I have a dataframe with the following structure (See example). The dots after OperatedIn2007 column signify multiple columns with same name, changing only the year (e.g OperatedIn2008, OperatedIn2009, etc.).

I wish to do the following procedure:

  • If the group is 1, then add one in all columns whose names start with OperatedIn.

The expected result should be similar to the one presented in the desired output.

A nonscalable solution would be to use:

df <- df %<%
   mutate(OperatedIn2006 = ifelse(group == 1, 1, 0)) %<%
   [...]

I imagine there is some slick solution using dplyr or data.table, but I could not think of it myself.

Example

 ID  group OperatedIn2006 OperatedIn2007 ...
 1     1              0              0
 2     2              0              0
 3     3              0              0
 4     4              0              0
 5     1              0              0
 6     2              0              0

Desired output

 ID  group OperatedIn2006 OperatedIn2007 ...
 1     1              1              1
 2     2              0              0
 3     3              0              0
 4     4              0              0
 5     1              1              1
 6     2              0              0

CodePudding user response:

We could use across with an ifelse statement:

library(dplyr)

df %>% 
  mutate(across(-c(ID, group), ~ifelse(group==1, 1, .)))
  ID group OperatedIn2006 OperatedIn2007
1  1     1              1              1
2  2     2              0              0
3  3     3              0              0
4  4     4              0              0
5  5     1              1              1
6  6     2              0              0
  • Related