placing mean,total and max together in a table in r

前端 未结 3 1845
终归单人心
终归单人心 2021-01-21 15:21

I have some simple commands looking into totals, means and maximums of a variable whilst another variable is an assigned value:

sum(data[data$var1==1,]$var2)
mea         


        
3条回答
  •  余生分开走
    2021-01-21 16:00

    I recommend checking out the data.table package, which is like a beefed-up version of data frames. One thing it does really well (and quickly, if you have a lot of data) is summaries like this.

    library(data.table)
    as.data.table(mtcars)[, list(sum=sum(mpg), mean=mean(mpg), max=max(mpg)),
                          by=cyl][order(cyl)]
    #   cyl   sum     mean  max
    #1:   4 293.3 26.66364 33.9
    #2:   6 138.2 19.74286 21.4
    #3:   8 211.4 15.10000 19.2
    

    If you want to summarize by more than one variable, just use something like by=list(cyl,vs,otherColumnNamesHere).

提交回复
热议问题