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:
Asked
Active
Viewed 25 times
1 Answers
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