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). 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.
Can someone please help??
The if
statement isn't vectorized. help("if")
does say on cond
in if (cond) expr
A length-one logical vector that is not NA. Conditions of length greater than one are accepted with a warning, but only the first element is used. Other types are coerced to logical if possible, ignoring any class.
You can try something using ifelse()
for vectors:
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: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". Only for those rows the contents of columns emotion
and polarity
is changed. 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"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.