R language, calculating the mean of an element in data.frame

topic description

data source, the diamonds, preview of the ggplot2 package is as follows

mean(diamonds[which(diamonds$cut=="Ideal"),]$price)

problem description

1, is there a more convenient way to calculate the mean value of the y-axis of a bar chart in ggplot2?
2, is there a better way to replace it in off-table calculation?

Thank you for asking questions for the first time.

Oct.25,2021

diamonds %>%
dplyr::group_by(cut) %>%
dplyr::mutate(avg_price = mean(price)) %>%
dplyr::ungroup() %>%
ggplot2::ggplot(aes(x = cut,y=avg_price)) + ggplot2::geom_point()
Menu