簡體   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