计算与第二个数据帧 R 匹配的一个数据帧中一组列值的出现次数

counting number of occurrences of a set of column values in one dataframe matching a second dataframe R

我有 2 个数据帧,我想计算第一个数据帧中相应行中第二个数据帧中列的出现次数:

> 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

检查必须收到我在设计中在actconjoint找到模式的次数。

所以在这种情况下,设计中的第 6 行必须接收 2,因为它在 actconjoint 中出现了两次。

我试过了:

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))

但我最好只是在检查栏中输入“1”!

您可以为两个数据帧创建一个唯一键,并计算每个数据帧在另一个数据帧中出现的次数。

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