String compare in "if-clause" in loop in R leads to "the condition has length > 1 and only the first element will be used"?
The problem is that strsplit
produces a list of split strings (in this case with length 1, because you only gave it a single string to split).
ss <- strsplit("A text I want to display with spaces", " ")
for (i in ss[[1]]) {
if (i=="want") print("yes")
}
You can see what's going on if you just print the elements:
for (i in ss) {
print(i)
}
the first element is a character
vector.
Depending on what you're doing you might also consider vectorized comparisons such as ifelse(ss=="want","yes","no")
yossarian
Updated on October 31, 2020Comments
-
yossarian over 3 years
I am puzzled by this behavior in R. I just want to do a simple string compare of a list of strings produced by strsplit. So do not understand why the following first two code pieces do what I expected, while the third is not.
> for (i in strsplit("A text I want to display with spaces", " ")) { print(i) } [1] "A" "text" "I" "want" "to" "display" "with" "spaces"
Ok, this makes sense ...
> for (i in strsplit("A text I want to display with spaces", " ")) { print(i=="want") } [1] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE
Ok, this too. But, what is wrong with the following construction?
> for (i in strsplit("A text I want to display with spaces", " ")) { if (i=="want") print("yes") } Warning message: In if (i == "want") print("yes") : the condition has length > 1 and only the first element will be used
Why doesn't this just print "yes" when the fourth word is encountered? What should I change to have this desired behavior?