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?
Using String.equalsIgnoreCase() : The String.equalsIgnoreCase() method compares two strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and the contents of both the Strings are same ignoring case, else false. Syntax: str2.equalsIgnoreCase(str1);
Compare String With the Java if Statement Using the equal() Function. Through the equal() function, we can compare the content of the two strings. It will see if the content is similar. It's case sensitive, but you can also ignore the case sensitivity by using the equalsIgnoreCase() function instead.
Time Complexity: O(min(n,m)) where n and m are the length of the strings. Auxiliary Space: O(max(n,m)) where n and m are the length of the strings.
To run an if-then statement in R, we use the if() {} function. The function has two main elements, a logical test in the parentheses, and conditional code in curly braces. The code in the curly braces is conditional because it is only evaluated if the logical test contained in the parentheses is TRUE .
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With