简体   繁体   English

如何根据r中的条件重新编码因子

[英]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. 如果列 ID 的值为 x 或 y,则应将其重命名为 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.您应该使用矢量化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.

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