我有一張如下圖所示的表格,我試圖用簡單的if語句僅在食物是「桔子」的情況下返回國家名稱。第三列是期望的結果,第4列是我在R.r如果語句返回級別數字而不是級別文本
在Excel中得到公式將是:
=IF(A2="Oranges",B2,"n/a")
我已經使用下列R-代碼來生成了「oranges_country」變量:
table$oranges_country <- ifelse (Food == "Oranges", Country , "n/a")
[按照上述圖像]的代碼返回電平的數目(例如,6)在所述等級列表「國家」,而塔n'國家'本身(例如「西班牙」)。我明白這是從哪裏來的(下面摘錄中的位置),但是使用幾個嵌套的if語句時尤其是一種痛苦。
levels(Country)
[1] "California" "Ecuador" "France" "New Zealand" "Peru" "Spain" "UK"
必須有一個簡單的方法來改變這???
的要求,在註釋:dput(表)輸出如下: dput(table) structure(list(Food = structure(c(1L, 1L, 3L, 1L, 1L, 3L, 3L, 2L, 2L), .Label = c("Apples", "Bananas", "Oranges"), class = "factor"), Country = structure(c(3L, 7L, 6L, 4L, 7L, 6L, 1L, 5L, 2L), .Label = c("California", "Ecuador", "France", "New Zealand", "Peru", "Spain", "UK" ), class = "factor"), Desired_If.Outcome = structure(c(2L, 2L, 3L, 2L, 2L, 3L, 1L, 2L, 2L), .Label = c("California", "n/a", "Spain"), class = "factor"), oranges_country = c("n/a", "n/a", "6", "n/a", "n/a", "6", "1", "n/a", "n/a"), desiredcolumn = c(NA, NA, 6L, NA, NA, 6L, 1L, NA, NA)), .Names = c("Food", "Country", "Desired_If.Outcome", "oranges_country", "desiredcolumn"), row.names = c(NA, -9L), class = "data.frame")
謝謝Max。這是我在我的代碼提取上面'table $ oranges_country < - ifelse(Food ==「Oranges」,Country,「n/a」)''所做的事情。我剛剛嘗試過你的輕微變體,它給出了相同的結果'> desiredcolumn [1]不適用6不適用6 1不適用' – Rob
請問您可以使用dput(table)發佈表的輸出。如果它有很多行,那麼只會給我們前10行。 – MaxPD
你可以先請做--'表$國家<-as.character(表$國家)',然後運行ifelse代碼。 – MaxPD