The tidy way of doing it is using dplyr and broom:
library(dplyr)
library(broom)
df <- data %>%
group_by(Product_type) %>%
do(tidy(t.test(.$Price_Online,
.$Price_Offline,
mu = 0,
alt = "two.sided",
paired = TRUE,
conf.level = 0.99))))
Much more readable than my base r solution, and it handles the column names for you!
EDIT
A more idiomatic way to do it rather than using do
(see r4ds) is to use nest
to create nested dataframes for each product type, then run a t-test for each nested dataframe using map
from purrr
.
library(broom)
library(dplyr)
library(purrr)
library(tidyr)
t_test <- function(df, mu = 0, alt = "two.sided", paired = T, conf.level = .99) {
tidy(t.test(df$Price_Offline,
df$Price_Online,
mu = mu,
alt = alt,
paired = paired,
conf.level = conf.level))
}
d <- df %>%
group_by(Product_type) %>%
nest() %>%
mutate(ttest = map(data, t_test)) %>%
unnest(ttest, .drop = T)