I have the following data frame (df)
df <- data.frame( TTMENT = c("Group_1","Group_1","Group_1","Group_2","Group_2","Group_2","Group_3","Group_3","Group_3","Group_4","Group_4","Group_4"),
D8 = c(40.3,37.4,44.8,39.6,40.6,41.1,38.5,41.6,41.8,43.6,43.1,41.6),
D9 = c(41.1,36.9,44.1,39.6,41.2,42.1,39.2,41.6,41.8,42.0,42.7,40.8),
D10 = c(41.5,37.1,44.4,39.4,40.8,41.2,39.9,41.5,42.4,42.4,42.7,41.9))
# A tibble: 12 x 4
TTMENT D8 D9 D10
<chr> <dbl> <dbl> <dbl>
1 Group_1 40.3 41.1 41.5
2 Group_1 37.4 36.9 37.1
3 Group_1 44.8 44.1 44.4
4 Group_2 39.6 39.6 39.4
5 Group_2 40.6 41.2 40.8
6 Group_2 41.1 42.1 41.2
7 Group_3 38.5 39.2 39.9
8 Group_3 41.6 41.6 41.5
9 Group_3 41.8 41.8 42.4
10 Group_4 43.6 42 42.4
11 Group_4 43.1 42.7 42.7
12 Group_4 41.6 40.8 41.9
Group 1 is control data against which I need to compare (via t-test) data from groups 2, 3 and 4. I'm trying to use dplyr (groupby / summarize) to show mean and t-test p-value, and the mean should have an "*" if p<0.05. The intended output is as follows:
D8 D9 D10
Group_1 mean XX.X XX.X XX.X
Group_2 mean XX.X XX.X *XX.X
Group_2 p 0.XX 0.XX 0.03
Group_3 mean XX.X XX.X XX.X
Group_3 p 0.XX 0.XX 0.XX
Group_4 mean XX.X *XX.X XX.X
Group_4 p 0.XX 0.01 0.XX
I'm trying to achieve this with the following code:
# Save control data in a separate data frame
control <- df%>%
filter(TTMENT == "Group_1") %>%
select(-TTMENT)
# function to do the actual job
compare_means <- function(x) {
p <- t.test(control,x)$p.value # this bit is not doing what is intended
data_mean <- sprintf("%.1f", mean(x, na.rm=TRUE))
if (p < 0.05) {
significant = "*" } else { significant = "" }
data_mean <- paste(significant, data_mean, sep="")
# Next line also triggers error. It is not possible to return two lines to summarize?
result <- data.frame(c(data_mean, p), row.names("mean", "p"), stringAsFactors=FALSE)
return(result)
}
# dplyr part
stack %>%
group_by(TTMENT) %>%
summarize(across(1:3, ~ compare_means(.) ))
I don't know how to handle the t-test comparisons (each not Group_1 against Group_1 [control])
Furthermore, is it possible to achieve what I intend to in one go? or should I do a dplyr groupby/summrize step for each row of results I need, i.e. one for p values and another one for means, and possibly another one for any other statistic I might need?