Home > Enterprise >  Summarise all rows from several columns
Summarise all rows from several columns

Time:08-22

I have a dataframe that looks as following:

1999  2000   2001  2002  2003  2004  2005  2006
57     42     34    24    54    34    34    43
76     32     34    35    32    42    23    33
53     31     85    65    25    21    34    21
24     24     24    32    65    45    54    45
# With 27 more rows

What I would like to do is to summarise all rows so the dataframe looks like this. Using the dplyrpackage there should be some summarise function but the one I've tried (summarise_all()) doesn't work.

1999  2000   2001  2002  2003  2004  2005  2006
524    432    432   543   231   432   432   541

CodePudding user response:

Base R:

sapply(df, function(var) sum(unique(var)))

or:

We could use map_dbl()

library(purrr)
library(dplyr)

df %>% 
  map_dbl(~ sum(.x))
X1999 X2000 X2001 X2002 X2003 X2004 X2005 X2006 
  210   129   177   156   176   142   145   142 

CodePudding user response:

Another Base R option using colSums for only numeric columns:

df <- read.table(text = "1999  2000   2001  2002  2003  2004  2005  2006
57     42     34    24    54    34    34    43
76     32     34    35    32    42    23    33
53     31     85    65    25    21    34    21
24     24     24    32    65    45    54    45", header = TRUE)

colSums(Filter(is.numeric, df))
#> X1999 X2000 X2001 X2002 X2003 X2004 X2005 X2006 
#>   210   129   177   156   176   142   145   142

Created on 2022-08-21 with reprex v2.0.2

  •  Tags:  
  • r
  • Related