aman aman - 3 years ago 53
R Question

To count the number of strings in one column common with strings in other column

i Have a df as
df1:

V1 |V2
------+----------
a,b,c|x,y,z,w,t,a
c,d |d,z,c,t
a,b,d|a,f,t,b,d


such that count of string in V1 is always under 3. I need a code so that it can tell me the number of string common with V2

V1 |V2 |Count
------+-----------+--------
a,b,c|x,y,z,w,t,a|1
c,d |d,z,c,t |2
a,b,d|a,f,t,b,d |3


Please help

Answer Source

Try this:

mapply(function(x,y) sum(x %in% y),
   strsplit(df$V1,","),strsplit(df$V2,","))
#[1] 1 2 3

Data

df<-structure(list(V1 = c("a,b,c", "c,d", "a,b,d"), V2 = c("x,y,z,w,t,a", 
"d,z,c,t", "a,f,t,b,d")), .Names = c("V1", "V2"), row.names = c(NA, 
-3L), class = "data.frame")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download