2015-12-30 61 views
0

我有一張如下圖所示的表格,我試圖用簡單的if語句僅在食物是「桔子」的情況下返回國家名稱。第三列是期望的結果,第4列是我在R.r如果語句返回級別數字而不是級別文本

enter image description here

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

回答

0

嘗試ifelse循環。首先,改變表$國家對字符()

table$Country<-as.character(Table$Country) 
table$desiredcolumn<-ifelse(table$Food == "Oranges", table$Country, NA) 

這裏是我的版本:

Food<-c("Ap","Ap","Or","Ap","Ap","Or","Or","Ba","Ba") 
Country<-c("Fra","UK","Sp","Nz","UK","Sp","Cal","Per","Eq") 
Table<-cbind(Food,Country) 
Table<-data.frame(Table) 
Table$Country<-as.character(Table$Country) 
Table$DC<-ifelse(Table$Food=="Or", Table$Country, NA) 
Table 

Food Country DC 
1 Ap  Fra <NA> 
2 Ap  UK <NA> 
3 Or  Sp Sp 
4 Ap  Nz <NA> 
5 Ap  UK <NA> 
6 Or  Sp Sp 
7 Or  Cal Cal 
8 Ba  Per <NA> 
9 Ba  Eq <NA> 
+0

謝謝Max。這是我在我的代碼提取上面'table $ oranges_country < - ifelse(Food ==「Oranges」,Country,「n/a」)''所做的事情。我剛剛嘗試過你的輕微變體,它給出了相同的結果'> desiredcolumn [1]不適用6不適用6 1不適用' – Rob

+0

請問您可以使用dput(table)發佈表的輸出。如果它有很多行,那麼只會給我們前10行。 – MaxPD

+0

你可以先請做--'表$國家<-as.character(表$國家)',然後運行ifelse代碼。 – MaxPD

0

試試這個(如果你的表稱爲table):

table[table$Food=="Oragnes", ] 
+0

感謝瑪塔,這的確是所謂的表!這只是返回與Orange相關的那3行的過濾表? (不知道如何在包含註釋格式的表格中包含表格) – Rob

+0

如果您只想爲這些選擇的國家/地區列,請嘗試:'table [table $ Food ==「Oragnes」,] $ Country' – Marta

+0

Ahh我明白了。但是,讓我們說,在我的真實例子中,我有很多列,我試圖建立複雜的嵌套if語句,以便我可以對此進行'pivot'樣式分析,所以相反,我的r代碼可能類似於'table $ oranges_country < - ifelse(Food ==「Oranges」,Country,ifelse(Food ==「Apples」,OtherVariable1,ifelse(Food ==「Bananas」,OtherVariable2,OtherVariable3)))''所以我認爲最簡單的方法是在一列。 – Rob