2015-05-15 74 views
0

我有一個data.frame(DL),其中一個列名是水果,它就像c(「apple」,「lemon」,「orange」,「others」)。所以我想改變這個列的級別,以便圖例的順序(當我創建圖)將遵循我想要的順序。這裏是我的代碼「other」變成「NA」

DL$fruit <- factor(DL$fruit, levels=c("lemon", "apple", "orange", "others")) 

但是,當我使用視圖(DL)後查看此數據時,「其他」將更改爲「NA」。當我gpplot這個,它不會顯示「其他人」的酒吧。有沒有人有一個想法是怎麼回事以及如何解決它?謝謝。

+2

有一個機會,有多餘的空格在'$ DL列fruit'? – A5C1D2H2I1M1N2O1R2T1

+0

@AnandaMahto你是對的!當我從「其他」變成「其他人」時,它就起作用了。謝謝。 – kelvinfrog

+0

@kelvinfrog,好的。我已經將其添加爲答案。 – A5C1D2H2I1M1N2O1R2T1

回答

2

如果您的數據不是很乾淨 - 例如,如果輸入值周圍有多餘的空白,有時會發生這種情況。

下面是一個例子:

fruit <- c("apple", "lemon", "orange", "others", "others ") ## note the last two values 
factor(fruit, levels=c("lemon", "apple", "orange", "others")) 
# [1] apple lemon orange others <NA> 
# Levels: lemon apple orange others 

現在,讓我們去掉空白:如果你想檢查源數據和尋找空白

newFruit <- gsub("^\\s+|\\s+$", "", fruit) 
factor(newFruit, levels = unique(newFruit)) 
# [1] apple lemon orange others others 
# Levels: apple lemon orange others 

,有時它有助於使用print,與quote = TRUE

print(fruit, quote = TRUE) 
# [1] "apple" "lemon" "orange" "others" "others " 

另外,grepl也可能是使用的:

grepl("^\\s+|\\s+$", fruit) 
# [1] FALSE FALSE FALSE FALSE TRUE