r if 语句 returns 级别数而不是级别文本

r if statement returns number of level rather than the level text

我有一个如下图所示的 table,我正在尝试使用一个简单的 if 语句来 return 国家名称,仅在食物 "Oranges" 的情况下。第 3 列是期望的结果,第 4 列是我在 R 中得到的结果。

在 excel 中,公式为:

=IF(A2="Oranges",B2,"n/a")

我使用以下 r 代码生成 "oranges_country" 变量:

table$oranges_country <- ifelse (Food == "Oranges", Country , "n/a")

[如上图] 代码 return 是 'Country' 级别列表中的级别编号(例如 6),而不是 'Country' 本身(例如 "Spain").我知道这是从哪里来的(摘录中的位置如下),但是这很痛苦,尤其是在使用多个嵌套的 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")

试试这个(如果你的 table 被称为 table):

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

尝试 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>