3

如果您的唯一列 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")
4

3 回答 3

5

这应该工作

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

DF 是你的 data.frame

ddplyplyr包中使用

ddply(DF, .(colID), numcolwise(sum))

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

使用acastdcastreshape2包中使用

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
于 2012-09-11T14:28:05.273 回答
3

这是一个data.table解决方案。by 列是因子还是字符都没有关系。

library(data.table)
DT <- as.data.table(data)
# Calculates the sum of columns col1, ..., col3
# and mean of col4
merge(DT[, lapply(.SD, sum),by = colID, .SDcols =paste0('col', 1:3)], 
      DT[, lapply(.SD, mean),by = colID, .SDcols ='col4'], 
  by = 'colID')
于 2012-10-25T02:36:48.057 回答
1
library(reshape2)
melted_data <- melt(df, id.vars = "colID")
dcast(melted_data, colID ~ variable, sum)
于 2012-09-11T14:31:07.097 回答