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?
The problem is that
strsplitproduces a list of split strings (in this case with length 1, because you only gave it a single string to split).You can see what’s going on if you just print the elements:
the first element is a
charactervector.Depending on what you’re doing you might also consider vectorized comparisons such as
ifelse(ss=="want","yes","no")