如果在单独的列中满足条件,则重命名因子变量

时间:2015-02-20 20:47:04

标签: r dplyr

我的df看起来像这样:

df <- data.frame(
    A = sample(c("Dog", "Cat", "Cat", "Dog", "Fish", "Fish")),
    B = sample(c("Brown", "Black", "Brown", "Black", "Brown", "Black")))
df

   A      B     
1  Dog    Brown
2  Cat    Black
3  Cat    Brown
4  Dog    Black
5  Fish   Brown
6  Fish   Black

我想重命名(最好使用dplyr)因子变量&#34; Fish&#34; to&#34; Dog&#34;每当条件&#34;布朗&#34;在第二栏中表示满意。

   A      B     
1  Dog    Brown
2  Cat    Black
3  Cat    Brown
4  Dog    Black
5  Dog    Brown  #rename here
6  Fish   Black

1 个答案:

答案 0 :(得分:2)

您可以使用replace

df %>% mutate(A = replace(A, which(A == "Fish" & B == "Brown"), "Dog"))
#     A     B
#1  Cat Black
#2 Fish Black
#3  Dog Black
#4  Dog Brown
#5  Cat Brown
#6  Dog Brown

这是一个data.table版本:

library(data.table)
setDT(df)[A == "Fish" & B == "Brown", A := "Dog"]