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

前端 未结 3 1842
终归单人心
终归单人心 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 15:49

    You need to use cbind for that.

    cbind(sum(data[data$var1==1,]$var2),mean(data[data$var1==1,]$var2),max(data[data$var1==1,]$var2))
    

    Example using mtcars data

    mydata<-mtcars  
      l<-cbind(sum(mydata[mydata$cyl==4,]$mpg),mean(mydata[mydata$cyl==4,]$mpg),max(mydata[mydata$cyl==4,]$mpg))
    l<-data.frame(l)
    names(l)<-c("sum","mean","max")
    > l
        sum     mean  max
    1 293.3 26.66364 33.9
    

    There is a ddply function from plyr package that does all for each categories of var1 (here cyl)

    library(plyr)
    ddply(mydata,.(cyl),summarize, sum=sum(mpg),mean=mean(mpg), max=max(mpg))
    
     ddply(mydata,.(cyl),summarize, sum=sum(mpg),mean=mean(mpg), max=max(mpg))
      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
    

提交回复
热议问题