Aggregate R sum

后端 未结 3 747
遥遥无期
遥遥无期 2020-12-11 09:34

I\'m writting my first program in R and as a newbie I\'m having some troubles, hope you can help me.

I\'ve got a data frame like this:

> v1<-c         


        
相关标签:
3条回答
  • 2020-12-11 09:47

    This is fairly straightforward with the plyr library.

    library("plyr")
    ddply(datos, .(Position), colwise(sum))
    

    If you have additional non-numeric columns that shouldn't be averaged, you can use

    ddply(datos, .(Position), numcolwise(sum))
    
    0 讨论(0)
  • 2020-12-11 09:49
    ag_df <-- aggregate(.~Position,data=datos,sum)
    

    should give you a data frame containing the sums of the "a" values for each of the positions. The trick here is the . in the formula represents a list of all the "non-grouping" variables in the formula.

    Note that you can get much the same result with:

    sumdf <- rowsum(datos,datos$Position,na.rm=T)
    

    Except that includes the sums of the positions as well!

    If you DON'T want all non-group columns aggregated, you can use cbind as in:

    sumdf1 <- aggregate(cbind(a1,a3)~datos$Position,datos,sum)
    

    That sums only the a1 and a3 columns.

    0 讨论(0)
  • 2020-12-11 10:05

    You need to tell the aggregate function to use sum, as the default is for it to get the mean of each category. For example:

    aggregate(datos[,c("a1","a2","a3")], by=list(datos$Position), "sum")
    
    0 讨论(0)
提交回复
热议问题