我有一张如下图所示的表格,我试图使用简单的if语句仅在食物是“橘子”的情况下返回国家名称。第3列是期望的结果,第4列是我在R中得到的。
在excel中,公式为:
=IF(A2="Oranges",B2,"n/a")
我使用以下r代码生成“oranges_country”变量:
table$oranges_country <- ifelse (Food == "Oranges", Country , "n/a")
[根据上图]代码返回“国家”级别列表中级别(例如6)的编号,而不是“国家”本身(例如“西班牙”)。我理解它来自何处(提取中的位置如下),但特别是当使用多个嵌套的if语句时,这是一种痛苦。
levels(Country)
[1] "California" "Ecuador" "France" "New Zealand" "Peru" "Spain" "UK"
必须有一个简单的方法来改变这个???
根据评论中的要求:dput(table)输出如下:
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 :(得分:0)
试试这个(如果您的表名为table
):
table[table$Food=="Oragnes", ]
答案 1 :(得分:0)
尝试ifelse
循环。首先,将Table $ Country更改为character()
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>