【问题标题】:counting number of occurrences of a set of column values in one dataframe matching a second dataframe R计算与第二个数据帧 R 匹配的一个数据帧中一组列值的出现次数
【发布时间】:2021-12-07 18:01:49
【问题描述】:

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

> 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”!

【问题讨论】:

  • 这行得通吗? sapply(1:nrow(design), function(x) sum(actconjoint[x,] == design[x,]))
  • @Skaqqs 错误在 Ops.data.frame(actconjoint[x, ], design[x, ]) : '==' 只为同样大小的数据帧定义
  • 您在考虑错误后是否再次尝试(确保两个数据帧具有相同的列数和顺序,即删除“检查”)?或者,您可以在方括号sapply(1:nrow(design), function(x) sum(actconjoint[x,cols] == design[x,cols])) 中指定列
  • 它似乎在计算。但我不确定计数属于哪些行。 &gt; cols&lt;-c("undIssue","feelConf","setup","undContex","undChang") &gt; sapply(1:nrow(design), function(x) sum(actconjoint[x,cols] == design[x,cols]))
  • 太棒了!每个元素对应design 中的一行。 design$check &lt;- sapply(1:nrow(design), function(x) sum(actconjoint[x,cols] == design[x,cols])) 是您期望的结果,我认为... 编辑:没关系,我刚刚意识到我误解了您的问题。我很抱歉。

标签: r dataframe join count apply


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 2021-08-02
    相关资源
    最近更新 更多