Home > Enterprise >  How to recode factor based on condition in r
How to recode factor based on condition in r

Time:11-07


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

CodePudding user response:

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)

  •  Tags:  
  • r
  • Related