data.frame中名称向量上的另一列的汇总和

时间:2014-11-28 15:54:05

标签: r dataframe

我有以下data.frame:

> DF <- data.frame(names = I(list(c("a", "b", "c"), c("a"), c("c", "d"))),
                   counts = c(1, 2, 3))
> DF
    names counts
1 a, b, c      1
2       a      2
3    c, d      3

如何获得总结每个名字总数的结果? 类似的东西:

name sum
a      3
b      1
c      4
d      3

1 个答案:

答案 0 :(得分:1)

尝试

 DF1 <- data.frame(name=unlist(DF$names),
          val=rep(DF$counts,sapply(DF$names, length)))

或者

 DF1 <- do.call(rbind,Map(data.frame, name=DF$names, val=DF$counts))

 aggregate(val~name, DF1, sum)
 #    name val
 #1    a   3
 #2    b   1
 #3    c   4
 #4    d   3

或者

  DF2 <- transform(stack(setNames(DF$names, DF$counts)),
                               ind=as.numeric(as.character(ind)))
  aggregate(ind~values, DF2, sum)