Home > OS >  counting number of occurrences of a set of column values in one dataframe matching a second datafram
counting number of occurrences of a set of column values in one dataframe matching a second datafram

Time:10-22

I have 2 dataframes where I want to count the number times the a of columns in the 2nd dataframe appears in the corresponding row at 1st dataframe :

> head(design)
  undIssue feelConf setup undContex undChang check
1        5        5     5         5        5     0
2        4        5     5         5        5     0
3        3        5     5         5        5     0
4        2        5     5         5        5     0
5        1        5     5         5        5     0
6        5        4     5         5        5     0

> head(actconjoint)
  undIssue feelConf setup undContex undChang
3        5        4     5         5        5
4        5        4     5         5        5
5        5        5     5         5        5
6        5        4     4         5        4
7        5        4     5         3        5
8        3        5     4         5        4

Check must receive the number of times I find the pattern at actconjoint in design.

So in this case the row 6 at design must receive 2 since it occurs twice at actconjoint.

I tried:

design$check <- 0

design$check <- 
  apply(design, 1, function(x) 
    ifelse(any(x[1] == actconjoint$undIssue & x[2] == actconjoint$feelConf & x[3] == actconjoint$setup & x[4] == actconjoint$undContex & x[5] == actconjoint$undChang), design$check<-design$check 1,design$check))

But the best I could be just to have "1"s into the check column!

CodePudding user response:

You can create a unique key for both the dataframes and count how many times each occur in another dataframe.

key1 <- do.call(paste, design[names(actconjoint)])
key2 <- do.call(paste, actconjoint)
design$check <- sapply(key1, function(x) sum(x == key2))
  • Related