aman
aman

Reputation: 151

Count the number of strings in one column common with strings in other column

I have the following data.frame:

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

where the count of strings in V1 is always under 3. I need an R code which tells the number of strings 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

Upvotes: 0

Views: 44

Answers (1)

nicola
nicola

Reputation: 24520

Try this:

mapply(function(x,y) sum(x %in% y),
   strsplit(df$V1,",", fixed=TRUE),strsplit(df$V2,",", fixed=TRUE))
#[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")

Upvotes: 1

Related Questions