【发布时间】: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]))中指定列 -
它似乎在计算。但我不确定计数属于哪些行。
> cols<-c("undIssue","feelConf","setup","undContex","undChang") > sapply(1:nrow(design), function(x) sum(actconjoint[x,cols] == design[x,cols])) -
太棒了!每个元素对应
design中的一行。design$check <- sapply(1:nrow(design), function(x) sum(actconjoint[x,cols] == design[x,cols]))是您期望的结果,我认为... 编辑:没关系,我刚刚意识到我误解了您的问题。我很抱歉。
标签: r dataframe join count apply