2

我正在尝试根据 DataFrame 中的另一列替换两列的值。我想使用 dplyr。DataFrame 的例子是:

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

如果 col1 = 'b',我想将 col2 和 col3 乘以 10,如果 col1 = 'c',我想将 col2 和 col3 乘以 20。

所需的输出应如下所示:

      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

我试过了:

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))

输出是:

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

我也试过:

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))

我又遇到了一个错误:

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

有人可以帮忙吗?谢谢 :)

4

1 回答 1

2

我们可以直接使用with而不是filtering 然后加入mutate_atcase_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

或者在dplyr1.0.0 中,可以用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
于 2020-04-23T18:43:01.070 回答