Nazer
Nazer

Reputation: 3774

Conditional mutating with dplyr for only some rows

I use ifelse with mutate to conditionally change variable names within a column. For example:

mutate(df, thiscol = ifelse((new == "oldname"), "newname", NA)

But I would like to change it so that instead of variables that don't fit the conditions turning into NA, they just stay as they were.

Upvotes: 2

Views: 1718

Answers (2)

jess
jess

Reputation: 534

mutate(df, thiscol = ifelse(new == "oldname", "newname", thiscol))

Upvotes: 3

akrun
akrun

Reputation: 887871

If we need to change only some elements and keep the rest as the same, then another option is replace

df %>%
    mutate(thiscol = replace(thiscol, new == "oldname", "newname"))

Upvotes: 2

Related Questions