繁体   English   中英

在R中使用ifelse函数重新编码分类变量的级别

[英]Using ifelse function in R to recode levels of categorical variable

我必须在R中使用“ ifelse”函数来取消编码变量中使用的值。

使用的数据帧是舞蹈。 变量是类型。 通过我收到的评论,这是我得到的:

ifelse(dance$Type=="Swg","Swing", 
ifelse(dance$Type=="Ldy","Lindy",
ifelse(dance$Type=="Blue","Blues",
else(dance$Type=="Contra","Contra"))))

我不断收到错误消息。 所有逗号正确吗? 另外,我正确结束了吗?

我不断收到错误消息,而且我应该以某种方式指定我正在使用的数据帧。

任何帮助将不胜感激。 谢谢。

如果Type是一个因素,那么您可以重命名级别并以这种方式提取它们(使用下面的f ):

f <- factor(c("Swg", "Ldy", "Blue", "Swg"))
# See the order of the levels by printing f. It's alphabetical
levels(f) <- c("Blues", "Lindy", "Swing")
as.character(f)

这将给

> f <- factor(c("Swg", "Ldy", "Blue", "Swg"))
> f
[1] Swg  Ldy  Blue Swg 
Levels: Blue Ldy Swg
> as.character(f)
[1] "Swg"  "Ldy"  "Blue" "Swg" 
> levels(f) <- c("Blues", "Lindy", "Swing")
> as.character(f)
[1] "Swing" "Lindy" "Blues" "Swing"

谢谢你的帮助。 我通过提到的技巧弄清楚了。 我需要命名一个数据框,并为未更改的数据提供替代解决方案。 我想出了:

Dance$new<-ifelse(dance$Type=="Swg","Swing", 
ifelse(dance$Type=="Ldy","Lindy",
ifelse(dance$Type=="Blue","Blues",
ifelse(dance$Type=="Contra","Contra",F))))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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