繁体   English   中英

R if 语句错误:条件长度 > 1 且仅使用第一个元素

[英]R if statement error: the condition has length > 1 and only the first element will be used

我有这个数据集,它看起来像这样:

我有这个看起来像这样的数据集。

这是我得到的错误:

这是我得到的错误

这是我的代码

read <- read.csv("sample.csv")

text2 <- read$text2
if(text2 == "No concern" | text2 == "No concern." | text2 == "No concerned" | text2 == "No concerns." | text2 == "No concerns") {
  read$emotion <- "unknown"
  read$polarity <- "neutral"
}else 
{
  read$emotion = emotion
  read$polarity = polarity
}

write.csv(text2, file = "test1.csv", row.names = TRUE)

我实际上想过使用 if 或 if else 语句来改变 csv 文件中的情绪和极性(见附图)。 我之所以要改变情绪和极性,是因为有些不正确。 因此,例如,如果在 text2 下,它是“不关心”、“不关心”或“不关心”,那么它的情绪应该是未知的,极性应该是中性的。

有人可以帮忙吗??

if语句未矢量化。 help("if")确实在if (cond) expr中说cond

非 NA 的长度为 1 的逻辑向量。 长度大于 1 的条件会被接受并带有警告,但仅使用第一个元素。 如果可能,其他类型被强制为逻辑类型,忽略任何类。

您可以尝试使用ifelse()来处理向量:

ifelse (text2 %in% c("No concern", "No concern.", "No concerned", "No concerns.", "No concerns"),
{read$emotion <- "unknown"; read$polarity <- "neutral"},
{read$emotion <- read$emotion; read$polarity <- read$polarity}
)

(因数据缺失而未运行)


编辑: data.table版本:

library(data.table)
read <- fread("sample.csv")
read[text2 %like% "^No concern", emotion := "unknown"]
read[text2 %like% "^No concern", polarity := "neutral"]

text2 %like% "^No concern"选择所有以 "No关注" 开头的read行。 只有那些行的emotionpolarity列的内容发生了变化。 所有其他行将保持原样。

注意:如果性能很重要,最后两个语句可以合并为一个赋值语句。

read[text2 %like% "^No concern", c("emotion", "polarity") := list("unknown", "neutral"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM