简体   繁体   English

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

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

I have to use the "ifelse" function in R to uncode values used in a variable. 我必须在R中使用“ ifelse”函数来取消编码变量中使用的值。

The data frame being used is dance. 使用的数据帧是舞蹈。 The variable is Type. 变量是类型。 Via comments I have received, here is what I have: 通过我收到的评论,这是我得到的:

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

I keep getting error messages. 我不断收到错误消息。 Are all of the commas correct? 所有逗号正确吗? Also, did I end it correctly? 另外,我正确结束了吗?

I keep getting error messages plus I'm supposed to specify the data frame I'm using somehow. 我不断收到错误消息,而且我应该以某种方式指定我正在使用的数据帧。

Any help would be greatly appreciated. 任何帮助将不胜感激。 Thank you. 谢谢。

If Type is a factor then you can rename the levels and extract them in this way (using f below): 如果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)

This will give 这将给

> 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"

Thanks for your help. 谢谢你的帮助。 I figured it out via tips that were mentioned. 我通过提到的技巧弄清楚了。 I needed to name a dataframe and give an alternate solution for data not changed. 我需要命名一个数据框,并为未更改的数据提供替代解决方案。 I came up with: 我想出了:

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