本文介绍了如果在单独的列中满足条件,则重命名因子变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的df:

I have a df that looks like this:

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

当第二列满足条件Brown时,我想将因子变量Fish更改为Dog。

I want to rename (with dplyr, preferably) the factor variable "Fish" to "Dog" whenever the condition "Brown" is satisfied in the second column.

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


推荐答案

您可以使用替换

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版本:

And here's a data.table version:

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

这篇关于如果在单独的列中满足条件,则重命名因子变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 04:02