简体   繁体   中英

Rstudio: Error while trying to use %in% operator in a dataframe

I want to find if a certain cell of a dataframe contains a word which exists in another cell of another dataframe. In specific:

geoplaces$name[1] has the value: Athens

adresses$Comments[1] has the value: Is he still in Athens?

But when I execute the follow script:

if(geoplaces$name[1] %in% adresses$Comments[1]){
  print("hello")
}else{print("error")}

I'm getting "error" as a result.

Any suggestions on what's wrong on this?

The %in% operator is looking for an exact match. In your case it is not true that "Athens" is contained in the vector consisting of the single element "Is he still in Athens?"

You are perhaps interested in substring matching. There are many ways to do this. You could try this using the grepl function:

if(grepl(geoplaces$name[1], adresses$Comments[1])) {
  print("hello")
} else {
  print("error")
} 

here you're checking if the first element of the vector ( geoplaces$name[1] ) is IDENTICAL TO the first element of another vector ( adresses$Comments[1] ). It compares if the strings are identical. But they aren't. If you want just the logical that the element (Athens ) is in the list, try regular expressions. So this should work: grepl(geoplaces$name[1], adresses$Comments[1])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM