[SOLVED] Count word matches between two variables

Issue

Assume two datasets A and B:

X1<- c('a', 'b','c')
place<-c('andes','brooklyn', 'comorin')
A<-data.frame(X1,place)

X2<-c('a','a','a','b','c','c','d')
place2<-c('andes','alamo','andes','brooklyn','comorin','camden','dover')
B<-data.frame(X2,place2)

I want to count how many times each word in A$place occurs in B$place2.

Solution

A possible solution:

library(tidyverse)

A %>% 
  rowwise %>% 
  mutate(n = sum(place == B$place2)) %>% 
  ungroup

#> # A tibble: 3 × 3
#>   X1    place        n
#>   <chr> <chr>    <int>
#> 1 a     andes        2
#> 2 b     brooklyn     1
#> 3 c     comorin      1

Answered By – PaulS

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *