简体   繁体   中英

How to recode factor based on condition in r


I'm trying to recode a factor based on a condition, however, I am not being able to.

Could you please help me?

Here is my code

if(df$ID = "x"){ df$ID <- recode_factor(df$ID, x == "Stack") }else if (df$ID = "y"){ df$ID <- recode_factor(df$ID, y=="Stack") } else { df$ID <- recode_factor(df$ID, "Other") }

I want to do the following:
if the column ID has a value x or y, it shall be renamed Stack. If it has any other value, it shall be renamed Other

You should use the vectorized ifelse rather than if , which only checks a single value.

Suppose your data looks like this:

df <- data.frame(ID = factor(c("y", "x", "a", "x", "x", "b", "y")))

df
#>   ID
#> 1  y
#> 2  x
#> 3  a
#> 4  x
#> 5  x
#> 6  b
#> 7  y

Then you can refactor with the single line:

df$ID <- factor(ifelse(df$ID == "x" | df$ID == "y", "Stack", "Other"))

or, equivalently:

df$ID <- factor(ifelse(df$ID %in% c("x", "y"), "Stack", "Other"))

Either of which result in:

df
#>      ID
#> 1 Stack
#> 2 Stack
#> 3 Other
#> 4 Stack
#> 5 Stack
#> 6 Other
#> 7 Stack

You can also use the following version, which doesn't require ifelse at all

df$ID <- factor(c("Other", "Stack")[df$ID %in% c("x", "y") + 1])

Created on 2021-11-06 by the reprex package (v2.0.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM