3
votes

I need to get col sum for all the columns and have the result in a data frame with colnames and their sum as two columns. But if I do this, column name seem to become index rather than a col itself.

demo=data.frame(a=runif(10),b=runif(10,max=2),c=runif(10,max=3))
as.data.frame(colSums(demo))

The undesired result:

   colSums(demo)
a      4.083571
b     11.698794
c     14.082574

The desired result:

colname colSums(demo)
a      4.083571
b     11.698794
c     14.082574

How can I add a heading to the column on the left while keep the shape as it is? Thanks.

5

5 Answers

6
votes

One possibility is to transpose the result with t()

data.frame(t(colSums(demo)))
                    a        b        c
colSums.demo. 5.782475 10.46739 18.46751

To change the name of the row in the output, we can use rownames, for instance like this:

`rownames<-`(data.frame(t(colSums(demo))), "myColsum")
             a        b        c
myColsum 5.782475 10.46739 18.46751
5
votes
> demo = data.frame(a=runif(10),b=runif(10,max=2),c=runif(10,max=3))
> df <- data.frame(colname = names(demo),colSums_demo=colSums(demo))
> print(df, row.names=F)
  colname colSums_demo
        a     4.754546
        b    12.488904
        c    18.152095
5
votes

Your desired output can be achieved with stack() and setNames():

setNames(nm=c('colname','colSums(demo)'),stack(colSums(demo))[2:1]);
##   colname colSums(demo)
## 1       a      4.083571
## 2       b     11.698794
## 3       c     14.082574
3
votes

Try this:

as.data.frame(lapply(demo, sum))

The result:

         a        b       c
1 6.400121 10.16047 10.6528
1
votes

We can use data.table with melt

library(data.table)
melt(setDT(demo)[, lapply(.SD, sum)])