emehex
emehex

Reputation: 10558

Renaming factor variables if a condition is satisfied in separate column

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

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

Upvotes: 0

Views: 1035

Answers (1)

talat
talat

Reputation: 70336

You could use 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

And here's a data.table version:

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

Upvotes: 2

Related Questions