I'm trying to make a table which looks at the percent response for different answers to survey questions. Answers are 1 (worst) to 5 (best), and I have succeeded in making the resulting table: Table 1
This is the dput() for Table 1
dput(t1)
structure(c(1.33196721311475, 0.867678958785249, 0.995024875621891,
0.544069640914037, 1.0498687664042, 0, 0.759219088937093, 0.66334991708126,
0.217627856365615, 0, 1.63934426229508, 6.83297180043384, 0.995024875621891,
0.870511425462459, 1.0498687664042, 19.5696721311475, 37.0932754880694,
26.6998341625207, 20.2393906420022, 20.4724409448819, 77.4590163934426,
54.4468546637744, 70.6467661691542, 78.1284004352557, 77.4278215223097
), .Dim = c(5L, 5L), .Dimnames = structure(list(c("A", "B", "C",
"D", "E"), c("1", "2", "3", "4", "5")), .Names = c("", "")))
Which is generated by:
t1<- t(apply(table(cleandata$`Event Name`, cleandata$Q1), 1, function(x) (x/sum(x)*100)))
How can I add a row at the bottom of the table with the Column Means? I've tried using add_row with tidyverse, rbind, and bind_rows, but nothing seems to be working. I was getting the column mean by colMean(t1), but perhaps I was going at it the wrong way?
CodePudding user response:
Using rbind
you could do:
rbind(t1, Mean = colMeans(t1))
#> 1 2 3 4 5
#> A 1.3319672 0.0000000 1.6393443 19.56967 77.45902
#> B 0.8676790 0.7592191 6.8329718 37.09328 54.44685
#> C 0.9950249 0.6633499 0.9950249 26.69983 70.64677
#> D 0.5440696 0.2176279 0.8705114 20.23939 78.12840
#> E 1.0498688 0.0000000 1.0498688 20.47244 77.42782
#> Mean 0.9577219 0.3280394 2.2775442 24.81492 71.62177
Created on 2022-05-19 by the reprex package (v2.0.1)
CodePudding user response:
I would prefer @stefan's solution, but if you want to use add_row
you need to transform it from a matrix to a dataframe, e.g.
library(dplyr)
tab <- cbind(names = rownames(t1), as_tibble(t1)) %>%
add_row(names = "Mean", t1 %>%
as_tibble() %>%
summarise(across(everything(), mean)))
colnames(tab)[1] <- ""
Output:
1 2 3 4 5
1 A 1.3319672 0.0000000 1.6393443 19.56967 77.45902
2 B 0.8676790 0.7592191 6.8329718 37.09328 54.44685
3 C 0.9950249 0.6633499 0.9950249 26.69983 70.64677
4 D 0.5440696 0.2176279 0.8705114 20.23939 78.12840
5 E 1.0498688 0.0000000 1.0498688 20.47244 77.42782
6 Mean 0.9577219 0.3280394 2.2775442 24.81492 71.62177