1

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))
4

2 回答 2

3

这与您要求的完全无关,但这是我的“splitstackshape”包中sapply使用的一种方法。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
于 2013-09-19T17:42:59.137 回答
1

或者更多的“手工”,如果您的数据框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)
于 2013-09-19T18:02:20.620 回答