Performing summary statistics on a data table in R (with two different classes)
17:53 27 Jul 2026

I'm trying to summarise a table which consists of a mix of records from two different classes. I just want to calculate the mean, SD, and perform a t-test on each of the columns. I have an answer, but it really looks terrible. I am wondering if there is a better way to do this?

I can show with an example.

library (dplyr)

##  I only need two categories
x <- mtcars[mtcars$cyl == 4 | mtcars$cyl == '8', ]

##  Calculate the mean and SD
y1 <- data.frame (t(aggregate (. ~cyl, x, mean)))
y2 <- data.frame (t(aggregate (. ~cyl, x, sd)))

colnames (y1) <- c("mean0", "mean1")
colnames (y2) <- c("sd0", "sd1")

##  Ugh...a bit ugly how I need to put the mean and SD together -- but it works
y <- cbind (y1$mean0, y2$sd0, y1$mean1, y2$sd1)
rownames (y) <- rownames (y1)
colnames (y) <- c ("mean0", "sd0", "mean1", "sd1")

##  This is worse with the t.test
z <- x %>% group_map (~ t.test (mpg ~ cyl, .x))

##  p-value is here:
z[[1]]$p.value

This is what y looks like:

> y
           mean0        sd0       mean1        sd1
cyl    4.0000000  4.0000000   8.0000000  8.0000000
mpg   26.6636364  4.5098277  15.1000000  2.5600481
disp 105.1363636 26.8715937 353.1000000 67.7713236
hp    82.6363636 20.9345300 209.2142857 50.9768855
drat   4.0709091  0.3654711   3.2292857  0.3723618
wt     2.2857273  0.5695637   3.9992143  0.7594047
qsec  19.1372727  1.6824452  16.7721429  1.1960138
vs     0.9090909  0.3015113   0.0000000  0.0000000
am     0.7272727  0.4670994   0.1428571  0.3631365
gear   4.0909091  0.5393599   3.2857143  0.7262730
carb   1.5454545  0.5222330   3.5000000  1.5566236

If that's the best I can do, I am ok with it. What bothers me more is z. This is what z looks like:

z[[1]]

    Welch Two Sample t-test

data:  mpg by cyl
t = 7.5967, df = 14.967, p-value = 1.641e-06
alternative hypothesis: true difference in means between group 4 and group 8 is not equal to 0
95 percent confidence interval:
  8.318518 14.808755
sample estimates:
mean in group 4 mean in group 8 
       26.66364        15.10000 

I guess there should be away to repeat this on every column, placing a column of p-values next to x (i.e., as a 5th column). But I am not sure how to do that. Any suggestions would be appreciated! Thank you!

r dplyr aggregate summary t-test