簡體   English   中英

使用 dplyr 根據 DataFrame 中的另一列更改行值

[英]Change row value based on another column in DataFrame using dplyr

我正在嘗試根據 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。

所需的 output 應如下所示:

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

output 是:

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

有人可以幫忙嗎? 謝謝:)

我們可以直接將mutate_atcase_when一起使用,而不是filter ing 然后加入

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

或者在dplyr 1.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM