如果您的唯一列 ID 是字符,您如何使用聚合?

aggregate(data, list(data$colID), sum)
Error in Summary.factor(c(1L, 1L), na.rm = FALSE) :
  sum not meaningful for factors

换性格..
data$colID<-as.character(data$colID)

aggregate(data, list(data$colID), sum)
Error in FUN(X[[1L]], ...) : invalid 'type' (character) of argument

ddply I get a similar error.
Error in FUN(X[[1L]], ...) :
  only defined on a data frame with all numeric variables

我只想通过 colID 聚合,我不想总结它。我希望所有其他列求和。
dput(data)
structure(list(colID = structure(c(1L, 1L, 1L, 2L, 2L), .Label = c("a",
"b"), class = "factor"), col1 = c(1, 0, 0, 0, 2), col2 = c(0,
1, 0, 2, 0), col3 = c(0, 0, 1, 0, 0), col4 = c(5, 5, 5, 7, 7)), .Names = c("colID",
"col1", "col2", "col3", "col4"), row.names = c(NA, -5L), class = "data.frame")

最佳答案

这应该工作

aggregate(x = DF[, -1], by = list(DF$colID), FUN = "sum")

DF 是你的 data.frame

使用 ddply 包中的 plyr
ddply(DF, .(colID), numcolwise(sum))

   colID col1 col2 col3 col4
1     a    1    1    1   15
2     b    2    2    0   14

使用 acast 包中的 dcastreshape2
acast( melt(DF), variable ~ colID, sum)  # a matrix
dcast( melt(DF), variable ~ colID, sum)  # a data.frame

Using colID as id variables
      a  b
col1  1  2
col2  1  2
col3  1  0
col4 15 14

编辑
使用 ddply 。不是那么优雅,但它有效!
 Sums <- ddply(DF[, -5], .(colID), numcolwise(sum))
 Mean <- ddply(DF[, c(1,5)], .(colID), numcolwise(mean))[,-1]
 cbind(Sums, col4_mean=Mean)
  colID col1 col2 col3 col4_mean
1     a    1    1    1         5
2     b    2    2    0         7

关于r - 按因子或字符聚合?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12371947/

10-12 17:30
查看更多