I've a data frame containing different items (and it's cost) and also it's subsequent groupings. I would like to run a T-Test for each item based on their groupings to see if their mean differs. Anybody knows how to do this in R without using the rstatix package? If possible, done in base R using lapply or looping. Tidyr and dplyr is fine.
A sample of the dataframe is as follow:
df = structure(list(Item = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("Book A",
"Book B", "Book C", "Book D"), class = "factor"), Cost = c(7L,
9L, 6L, 7L, 4L, 6L, 5L, 3L, 5L, 4L, 7L, 2L, 2L, 4L, 2L, 9L, 4L
), Grouping = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L,
1L, 1L, 2L, 2L, 1L, 2L, 2L, 1L), .Label = c("A", "B"), class = "factor")), class = "data.frame", row.names = c(NA,
-17L))
Item | Cost | Grouping |
---|---|---|
Book A | 7 | A |
Book A | 9 | B |
Book A | 6 | A |
Book A | 7 | B |
Book B | 4 | A |
Book B | 6 | B |
Book B | 5 | A |
Book B | 3 | A |
Book C | 5 | B |
Book C | 4 | A |
Book C | 7 | A |
Book C | 2 | B |
Book C | 2 | B |
Book D | 4 | A |
Book D | 2 | B |
Book D | 9 | B |
Book D | 4 | A |
The output should be a simple table (or any similar table) as follows
Item | P-Value (H0: Mean of group A = Mean of group B) |
---|---|
Book A | xxx |
Book B | xxx |
Book C | xxx |
Book D | xxx |
Using the rstatix package, the code will be (credits: Quinten)
library(dplyr)
library(rstatix)
df %>%
group_by(Item) %>%
t_test(Cost ~ Grouping)
I would like to achieve the same output but without using rstatix package as I often encounter issues with the broom package (dependent package of rstatix). Base package would be fine as I code with my phone sometimes.
Thank you!