【问题标题】:Using sapply to aggregate columns comma separated values使用 sapply 聚合列逗号分隔值
【发布时间】:2013-09-19 17:19:33
【问题描述】:

dA 有这样的数据表

id   group    startPoints       endPoints
1    A        4, 20, 50, 63,   8, 25, 60, 78
1    A        120, 300,        231, 332
1    B        500,             550
1    B        650, 800         700, 820
1    C        830, 900, 950    850, 920, 970

我想要实现的是在特定组中获得长度 (EndPoint - StartPoint) 的 SUM/MEAN/等,但无法与 sapply 一起使用

我的目标是得到表单的结果:

Group    SUM 
A        177
B        120
C        60

我正在尝试将两件事结合起来

 lengths <- strsplit(as.character(table$endPoints), ",", fixed=TRUE)

y <- factor(table$group)
tapply(lengths, y, sum)

但我被卡住了,无法让它工作。

添加样本数据

structure(list(id = c(1L, 1L, 1L, 1L, 1L), group = structure(c(1L, 
1L, 2L, 2L, 3L), .Label = c("A", "B", "C"), class = "factor"), 
startPoints = structure(c(2L, 1L, 3L, 4L, 5L), .Label = c("120,300,", 
"4,20,50,63,", "500,", "650,800,", "830,900,950,"), class = "factor"), 
endPoints = structure(c(4L, 1L, 2L, 3L, 5L), .Label = c("231,332,", 
"550,", "700,820,", "8,25,60,78", "850,920,970,"), class = "factor")), 
.Names = c("id", "group", "startPoints", "endPoints"), class = "data.frame", 
row.names = c(NA, -5L))

【问题讨论】:

  • dput您的样本数据。
  • 当然,我更新了我的问题。谢谢!
  • dput 中的列名和问题的其余部分不一致...

标签: r bioconductor sapply


【解决方案1】:

这与您要求的sapply 完全无关,但这是使用我的“splitstackshape”包中的concat.split.multiple 的一种方法。

首先,将数据拆分成半长格式:

library(splitstackshape)
mydf2 <- concat.split.multiple(mydf, split.cols = c("startPoints", "endPoints"), 
                               seps = ",", direction = "long")

计算“endPoints”和“startPoints”之间的差异:

mydf2$diffs <- mydf2$endPoints - mydf2$startPoints
head(mydf2)
#   id group .id time startPoints endPoints diffs
# 1  1     A   1    1           4         8     4
# 2  1     A   2    1         120       231   111
# 3  1     B   1    1         500       550    50
# 4  1     B   2    1         650       700    50
# 5  1     C   1    1         830       850    20
# 6  1     A   1    2          20        25     5

使用aggregate(或data.table,或tapply,或您最喜欢的聚合函数)来计算您想要的任何东西。

aggregate(diffs ~ group, mydf2, sum)
#   group diffs
# 1     A   177
# 2     B   120
# 3     C    60

【讨论】:

    【解决方案2】:

    或者多一点“手工”,如果您的数据框是xx,那么将端点拆分为单独的元素,计算出每行的长度

    endPoints = strsplit(as.character(xx$endPoints), ",", fixed=TRUE)
    startPoints = strsplit(as.character(xx$startPoints), ",", fixed=TRUE)
    len = sapply(endPoints, length)
    

    使用长度扩展原始数据框,取消列出以前压缩的元素

    yy = cbind(xx[rep(seq_len(nrow(xx)), len), c("id", "group")], 
                  startPoints=as.integer(unlist(startPoints)), 
                  endPoints=as.integer(unlist(endPoints)))
    

    之后aggregate 是你的朋友。

    aggregate(endPoints - startPoints ~ group, yy, sum)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      • 1970-01-01
      • 2015-08-24
      • 1970-01-01
      • 2021-07-02
      • 2013-07-03
      相关资源
      最近更新 更多