【问题标题】:Merge data frame by count in R在R中按计数合并数据帧
【发布时间】:2015-12-14 12:27:19
【问题描述】:

下面有两个数据框。

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

【问题讨论】:

  • y1:y2 计数是什么意思?
  • 你尝试了什么?为什么它不起作用?
  • 我认为基于count for y1:y2,看来y2:y3:y4应该是4。

标签: r merge subset


【解决方案1】:

我们可以用colSums 得到'df1' 的列和。使用grep 识别具有: 的“x”元素。然后,我们 split 基于索引 ('i1') 的 'x' 列,对每个 list 元素中的 'df1' 列进行子集化,使用 Reduce&amp; 以便我们只得到 TRUE当同一行的所有元素都是1时。获取sum,并根据创建的'v1'对象创建'count'列。

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

【讨论】:

  • 不错的解决方案。正在考虑类似的事情。
  • +1 真的很好!我想我会将它保留为一个衬里v1 &lt;- sapply(strsplit(setNames(as.character(df2$x), as.character(df2$x)), ':'), function(x) sum(Reduce(&,df1[x]))) 尽管可能首先使用colSums,然后仅在需要时使用sapply + sum(reduce) 可能更有效。
猜你喜欢
  • 2015-04-26
  • 2023-03-05
  • 2019-03-29
  • 2017-08-05
  • 1970-01-01
  • 2014-04-04
  • 2018-03-17
  • 1970-01-01
  • 2017-01-15
相关资源
最近更新 更多