To calculate the mean by group in R, we can use the group_by()
function from the dplyr package and then apply the mean()
function to the grouped data. To handle missing data, we can use the na.rm = TRUE
argument in the mean()
function.
Here's an example using the mtcars
dataset:
main.r201 chars11 lines
Output:
main.r103 chars7 lines
We can see that the missing data was ignored and the mean mpg was calculated for each group (cyl) separately.
gistlibby LogSnag