1
votes

I am trying to replace the values of two columns based on another column in DataFrame. I would like to use dplyr. The example of DataFrame is:

df <- data.frame(col1 = c('a', 'b', 'a', 'c', 'b', 'c'),
                 col2 = c(2, 4, 6, 8, 10, 12),
                 col3 = c(5, 10, 15, 20, 25, 30))
df

I want to multiply col2 and col3 by 10 if col1 = 'b' and col2 and col 3 by 20 if col1 = 'c'.

The desired output should be as the following:

      col1     col2     col3
1      a        2        5
2      b        40       100
3      a        6        15
4      c        160      400
5      b        100      250
6      c        240      600

I tried:

df %>% filter(., col1=='b') %>% mutate(.= replace(., col2, col2*10)) %>% mutate(.= replace(., col3, col3*10))
df %>% filter(., col1=='c') %>% mutate(.= replace(., col2, col2*20)) %>% mutate(.= replace(., col3, col3*20))

The output is:

Error in replace(., col2, col2*10): object 'col2' not found

I also tried:

df %>% mutate_at(vars(col2, col3), funs(ifelse(col1=='b', col2*10, col3*10))
df %>% mutate_at(vars(col2, col3), funs(ifelse(col1=='c', col2*20, col3*20))

I got an error again:

funs() is soft deprecated as of dplyr 0.8.0 ...

Can anyone help please? Thank you :)

1
The deprecation message is not an error.Axeman
Oh OK I didn't know that. Thank you Axeman!user13047041

1 Answers

1
votes

Instead of filtering and then joining we can directly use mutate_at with case_when

library(dplyr)
df %>% 
    mutate_at(vars(col2, col3), ~ 
       case_when(col1 == 'b' ~  .* 10, col1  == 'c' ~ .* 20, TRUE  ~ .))
#  col1 col2 col3
#1    a    2    5
#2    b   40  100
#3    a    6   15
#4    c  160  400
#5    b  100  250
#6    c  240  600

Or in the dplyr 1.0.0, it can be done with mutate/across

df %>%
   mutate(across(c(col2, col3), ~ 
       case_when(col1 == 'b' ~  .* 10, col1  == 'c' ~ .* 20, TRUE  ~ .)))
#  col1 col2 col3
#1    a    2    5
#2    b   40  100
#3    a    6   15
#4    c  160  400
#5    b  100  250
#6    c  240  600