下面有两个数据框。
set.seed(12345)
df1 <- data.frame(
y1 = sample(rep(c(0:1),length.out = 50)),
y2 = sample(rep(c(0:1),length.out = 50)),
y3 = sample(rep(c(0:1),length.out = 50)),
y4 = sample(rep(c(0:1),length.out = 50)),
y5 = sample(rep(c(0:1),length.out = 50)),
y6 = sample(rep(c(0:1),length.out = 50))
)
df2 <- data.frame(x = c("y1","y2","y1:y2","y2:y3:y4","y5","y6"))
我想合并这两个数据框,但合并的结果将显示每个元素的“1”计数。我的另一个问题是,在第二个数据框中,有些列有多个元素,用“:”分隔。这将使我很难自动执行此操作。下面是我要实现的表格
x count
1 y1 25
2 y2 25
3 y1:y2 11
4 y2:y3:y4 8
5 y5 25
6 y6 25
最佳答案
我们可以使用 colSums
获得 'df1' 的列式总和。使用 grep
识别具有 :
的 'x' 元素。然后,我们根据索引 ('i1') 拆分
'x' 列,在每个 list
元素中对 'df1' 列进行子集化,使用 Reduce
和 &
这样当同一行中的所有元素都为 1 时,我们只会得到 TRUE
。获取 sum
,并创建基于创建的“v1”对象的“计数”列。
v1 <- colSums(df1)
i1 <- grep(':', df2$x)
v1[i1] <- sapply(strsplit(as.character(df2$x[i1]), ':'),
function(x) sum(Reduce(`&`,df1[x])))
df2$count <- v1
关于r - 按 R 中的计数合并数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34267052/