How do I return multiple results in one table?

Viewed 45

I have a table of numeric variables:

| result_1|result_2|result_3|
|    3    |   11   |   9    |
|    2    |   15   |   5    |
|    14   |   3    |   2    |
|    1    |   19   |   7    |
|    3    |   3    |   9    |

I would like to return a table that shows min, max, and sum for each variable as below:

        |  Min  |  Max   |  Sum  |
result_1|  1    |  14    |  23   |
result_2|  3    |  19    |  41   |
result_3|  2    |  9     |  32   |

I have tried using the apply family below but doesn't work

sapply(df, function(x){
   return(c(min(x), max(x), sum(x))}
)
3 Answers

Try the code below

ops <- c(min = min, max = max, sum = sum)
t(sapply(df, function(x) sapply(ops, function(f) f(x))))

giving

    result_1 result_2 result_3
min        1        3        2
max       14       19        9
sum       23       51       32

Data

> dput(df)
structure(list(result_1 = c(3L, 2L, 14L, 1L, 3L), result_2 = c(11L, 
15L, 3L, 19L, 3L), result_3 = c(9L, 5L, 2L, 7L, 9L)), class = "data.frame", row.names = c(NA,   
-5L))

Instead of looping over the columns, loop over the names. Also name your concatenated elements. *apply results often have to be transposed.

t(sapply(names(d), function(x) c(min=min(d[x]), max=max(d[x]), sum=sum(d[x]))))
#          min max sum
# result_1   1  14  23
# result_2   3  19  51
# result_3   2   9  32

Data:

d <- structure(list(result_1 = c(3L, 2L, 14L, 1L, 3L), result_2 = c(11L, 
15L, 3L, 19L, 3L), result_3 = c(9L, 5L, 2L, 7L, 9L)), class = "data.frame", row.names = c(NA, 
-5L))

Or an option with tidyverse

library(dplyr)
library(tidyr)
df %>% 
  pivot_longer(cols  = everything()) %>%
  group_by(name) %>%
  summarise(across(value, list(min, max, sum)))
Related