0

I want to get the mean for each diet and period. Then I would like to collect the answers for the columns score1, score2 and score3 in a data frame. I have run the function with aggregate. Do you know any other way to do this? just want to know for learning!

set.seed(8)
id <- 1:6
diet <- rep(c("A","B"),3)
period <- rep(c(1,2),3)
score1 <- sample(1:100,6)
score2 <- sample(1:100,6)
score3 <- sample(1:100,6)

df <- data.frame(id,diet,period,score1, score2, score3)

medel <- function(i){
  df <- aggregate(df[,i]~ period + diet, FUN=mean, data=df)
  df
}

I want it to be collected in a data frame like this:

    score1 score2   score3
1 52.33333     50 19.66667
2 51.33333     55 56.66667
user11916948
  • 944
  • 5
  • 12

1 Answers1

1

One option would be to use dplyr:

df %>%
  select(-id) %>%
  group_by_at(vars(diet, period)) %>%
  summarise_all(~mean(.))
AlexB
  • 3,061
  • 2
  • 17
  • 19