0

I want to split the mtcars dataframe into list by using split() function and i want to ssplit using cyl column. Then I want to calculate the mean of each of the dataframe in the resulting list (example: mean of '8' dataframe in the list). How can I do it? I am beginner in R so need easy to understand solution please. My code:

enter image description here

sam
  • 37
  • 4

1 Answers1

1

With split first, you need to apply the mean to each of your subsets; you can do that with *apply functions. Here sapply takes as input the list of subsets and apply to every one the function function(x) mean(x$mpg).

split(mtcars, mtcars$cyl) |>
  sapply(function(x) mean(x$mpg))

A short version with tapply:

tapply(mtcars$mpg, mtcars$cyl, mean)

#       4        6        8 
#26.66364 19.74286 15.10000 
Maël
  • 45,206
  • 3
  • 29
  • 67