RStudio中使用%in%运算符匹配数据框单元格内容时出错的问题
Hey there! Let's break down why your code isn't working as expected and fix it up.
Why Your
%in% Check Fails The core issue is misunderstanding what the %in% operator does in R:
%in%checks if the entire left-hand element exists as a full, separate element in the right-hand vector. It does not scan for substring matches within a single string.- In your case, you're comparing
"Athens"against the full comment string"Is he still in Athens?". Since"Athens"isn't identical to that complete comment,%in%returnsFALSE, triggering yourelseblock.
The Fix: Check for Substring Matches
To verify if one string contains another as a substring, use R's grepl() function—it's built exactly for this scenario:
if(grepl(geoplaces$name[1], adresses$Comments[1])) { print("hello") } else { print("error") }
This will correctly output "hello" because grepl() scans the target comment string to see if the name substring appears anywhere inside it.
Bonus Tips
- For case-insensitive matches (e.g., catching
"athens"or"ATHENS"), add theignore.case = TRUEparameter:grepl(geoplaces$name[1], adresses$Comments[1], ignore.case = TRUE) - To run this check across entire columns (not just the first row),
grepl()works with vectors too. Ifgeoplaces$nameandadresses$Commentsare the same length, you can do:
This gives you a logical vector where each entry tells you if the corresponding name is present in the comment.matches <- grepl(geoplaces$name, adresses$Comments)
内容的提问来源于stack exchange,提问作者Stathis G.
相关产品推荐
相关产品推荐

