Matching rows by columns in R

I have a data frame with 2 columns of characters. I would like to find rows in which one column contains another, however grepl is weird. Any ideas?

> ( df <- data.frame(letter=c('a','b'),food = c('apple','pear','bun','beets')) )
  letter  food
1      a apple
2      b  pear
3      a   bun
4      b beets 

> grepl(df$letter,df$food)

[1]  TRUE  TRUE FALSE FALSE

but i want tft

Thanks.

+5
source share
2 answers

Thanks to Kevin’s suggestion to use,

> mapply (grepl, df $ letter, df $ food)

leads to the desired result.

+5
source

When I run my code, I get a warning:

Warning message:
In grepl(df$letter, df$food) :
  argument 'pattern' has length > 1 and only the first element will be used

This is confirmed ?greplunder pattern:

If a character vector of length 2 or more is supplied, 
the first element is used with a warning.

So grepl finds a in both the apple tree and the pear. This does not solve your problem (apply or one of its options?), But it explains the conclusion that you get.

+2
source

All Articles