对两个匹配的字符串/单词使用ifelse函数

时间:2019-02-08 15:42:45

标签: r if-statement

我的问题很简单。我有一个像这样的数据集:

     observed predicted probability result2
1     Head-up   Grazing   0.2727273   FALSE
2     Head-up   Grazing   0.7272727    TRUE
3     Head-up   Grazing   0.7272727    TRUE
4     Head-up   Grazing   0.5454545    TRUE
5     Head-up   Grazing   0.7272727    TRUE
6     Head-up   Grazing   0.4545455   FALSE
7     Head-up Vigilance   0.3636364   FALSE
8     Head-up   Grazing   0.3636364   FALSE
9     Head-up Vigilance   0.3636364   FALSE
10    Unknown   Grazing   0.3636364   FALSE
11     Moving   Head-up   0.4545455   FALSE
12     Moving   Head-up   0.3636364   FALSE

我通过使用results2函数成功创建了列ifelse的地方:

table$result1<-ifelse(table$probability>0.5,"TRUE","FALSE")

但是,我试图使用相同的函数来创建列result1,该列将是:

table$result1<-ifelse(table$observed=table$predicted, "POSITIVE", "NEGATIVE")`. 

我在Error: unexpected '='中遇到错误table$result1<-ifelse(table$observed=

实际上,如果observed列上的单词与同一行的predicted列上的单词匹配,我想有“ POSITIVE”,反之亦然。如果有,则为“ NEGATIVE”。 / p>

有什么想法吗?任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

就像@Sotos评论一样(很抱歉,我劫持了您的评论,但尚未发布正确答案),问题是您使用的是=而不是==

看看这个例子:

首先我生成测试数据集

df <- data.frame("observed" = rep(c("observed", "predicted"), 3), 
                 "predicted" = "observed", 
                 stringsAsFactors = F)

如下所示:

   observed predicted
1  observed  observed
2 predicted  observed
3  observed  observed
4 predicted  observed
5  observed  observed
6 predicted  observed

然后使用ifelse

df$result <- ifelse(df$observed == df$predicted, "POSITIVE", "NEGATIVE")

结果是

   observed predicted   result
1  observed  observed POSITIVE
2 predicted  observed NEGATIVE
3  observed  observed POSITIVE
4 predicted  observed NEGATIVE
5  observed  observed POSITIVE
6 predicted  observed NEGATIVE

同样,正如@Soto指出的那样,您的问题是存储在数据集中的数据类型。您有factors,应该是characters

在创建数据集时,我解决了添加stringsAsFactors = F的问题,这也可以与read.tableread.csv之类的功能一起使用。

另一种方法是使用@Soto建议的解决方案,就像

df$observed <- as.character(df$observed)
df$predicted <- as.character(df$predicted)

在使用ifelse函数之前。