[英]How to recode factor based on condition in r
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") }
You should use the vectorized ifelse
rather than if
, which only checks a single value.您应该使用矢量化
ifelse
而不是if
,后者只检查单个值。
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您也可以使用以下版本,它根本不需要
ifelse
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)由reprex 包( v2.0.0 ) 于 2021 年 11 月 6 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.