[英]R if statement error: the condition has length > 1 and only the first element will be used
I have this data set which looks something like this:我有这个数据集,它看起来像这样:
This is the error I got:这是我得到的错误:
This is my code这是我的代码
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)
I actually thought of using if or if else statements to change the emotions and polarity in the csv file (see picture attached).我实际上想过使用 if 或 if else 语句来改变 csv 文件中的情绪和极性(见附图)。 The reason why I want to change the emotion and polarity is because some are not correct.
我之所以要改变情绪和极性,是因为有些不正确。 So for example if under text2, it is "no concern", "no concerns", or "no concerned" it's emotion should be unknown and polarity should be neutral.
因此,例如,如果在 text2 下,它是“不关心”、“不关心”或“不关心”,那么它的情绪应该是未知的,极性应该是中性的。
Can someone please help??有人可以帮忙吗??
The if
statement isn't vectorized. if
语句未矢量化。 help("if")
does say on cond
in if (cond) expr
help("if")
确实在if (cond) expr
中说cond
A length-one logical vector that is not NA.
非 NA 的长度为 1 的逻辑向量。 Conditions of length greater than one are accepted with a warning, but only the first element is used.
长度大于 1 的条件会被接受并带有警告,但仅使用第一个元素。 Other types are coerced to logical if possible, ignoring any class.
如果可能,其他类型被强制为逻辑类型,忽略任何类。
You can try something using ifelse()
for vectors:您可以尝试使用
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}
)
(Not run due to missing data) (因数据缺失而未运行)
data.table
version: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"
selects all rows of read
which start with "No concern". text2 %like% "^No concern"
选择所有以 "No关注" 开头的read
行。 Only for those rows the contents of columns emotion
and polarity
is changed.只有那些行的
emotion
和polarity
列的内容发生了变化。 All other rows will stay as they were.所有其他行将保持原样。
NB: If performance matters, the last two statements could be combined into a single assignment statement.
注意:如果性能很重要,最后两个语句可以合并为一个赋值语句。
read[text2 %like% "^No concern", c("emotion", "polarity") := list("unknown", "neutral"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.