对于新手问题的道歉,仍然让DPLYR(和R通常如此)束之高阁。
我有以下数据集,并且我正在尝试计算条目数超过1的每个区域组的平均评分。
Area Rating
UK 5.256
Ireland 6.1465
Canada 6.1452
USA 6.14
Ireland 4.258
USA 3.154
我期望的返回数据为:
Area Count Average_Rating
Ireland 2 5.20255
USA 2 4.647
我尝试了以下代码,但是当我尝试执行“计数”列时(它返回所有区域的平均值)似乎下降了
df %>%
group_by (Area) %>%
mutate (count =n()) %>%
summarise (mean = mean(Average_Rating)) %>%
arrange(desc(mean))
我尝试按动词顺序进行操作,但没有成功。任何帮助,不胜感激!
答案 0 :(得分:3)
在filter
步骤之后,我们需要一个group_by
library(dplyr)
df1 %>%
group_by(Area) %>%
filter(n() > 1) %>%
summarise(Count = n(), Average_Rating = mean(Rating)) %>%
arrange(desc(Average_Rating))
# A tibble: 2 x 3
# Area Count Average_Rating
# <chr> <int> <dbl>
#1 Ireland 2 5.20
#2 USA 2 4.65
df1 <- structure(list(Area = c("UK", "Ireland", "Canada", "USA", "Ireland",
"USA"), Rating = c(5.256, 6.1465, 6.1452, 6.14, 4.258, 3.154)),
class = "data.frame", row.names = c(NA,
-6L))