Skip to content

Instantly share code, notes, and snippets.

@FlukeAndFeather
Created March 21, 2020 17:34
Show Gist options
  • Save FlukeAndFeather/279d1de4791c1fd19e20bb6715a625cb to your computer and use it in GitHub Desktop.
Save FlukeAndFeather/279d1de4791c1fd19e20bb6715a625cb to your computer and use it in GitHub Desktop.
Add a row at the end of a data frame with summaries for numeric colums
library(tidyverse)
set.seed(1024)
d <- tibble(
  a = letters[1:5],
  b = LETTERS[6:10],
  x = 1:5,
  y = (1:5)^2,
  z = runif(5)
)

col_summ <- function(tbl, f) {
  rbind(
    tbl,
    map(tbl, ~ if(is.numeric(.x)) f(.x) else NA)
  )
}
col_summ(d, sum)
#> # A tibble: 6 x 5
#>   a     b         x     y      z
#> * <chr> <chr> <int> <dbl>  <dbl>
#> 1 a     F         1     1 0.218 
#> 2 b     G         2     4 0.988 
#> 3 c     H         3     9 0.348 
#> 4 d     I         4    16 0.381 
#> 5 e     J         5    25 0.0210
#> 6 <NA>  <NA>     15    55 1.96
col_summ(d, mean)
#> # A tibble: 6 x 5
#>   a     b         x     y      z
#> * <chr> <chr> <dbl> <dbl>  <dbl>
#> 1 a     F         1     1 0.218 
#> 2 b     G         2     4 0.988 
#> 3 c     H         3     9 0.348 
#> 4 d     I         4    16 0.381 
#> 5 e     J         5    25 0.0210
#> 6 <NA>  <NA>      3    11 0.391

Created on 2020-03-21 by the reprex package (v0.3.0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment