Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate by factor or character?

Tags:

r

aggregate

How do you use aggregate if your unique column ID is a character?

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

Change to character..

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

I only want to aggregate by the colID, I dont want to sum it. I want all the other columns to sum.

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")
like image 509
user1652961 Avatar asked Oct 17 '25 10:10

user1652961


1 Answers

This should work

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

Where DF is your data.frame

Using ddply from plyr package

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

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

usign either acast or dcast from reshape2 package

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

EDIT Using ddply. Not so elegant, but it works!

 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
like image 63
Jilber Urbina Avatar answered Oct 20 '25 00:10

Jilber Urbina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!