我试图创建一个分组的摘要,报告每个组中的记录数,然后还显示一系列变量的含义。
我只能将如何做为两个独立的摘要,然后将它们合并在一起。这可以正常工作,但我想知道是否还有更优雅的方法可以做到这一点?
dailyn<-daily %>% # this summarises n
group_by(type) %>%
summarise(n=n()) %>%
dailymeans <- daily %>% # this summarises the means
group_by(type) %>%
summarise_at(vars(starts_with("d.")),funs(mean(., na.rm = TRUE))) %>%
dailysummary<-inner_join(dailyn,dailymeans) #this joins the two parts together
Run Code Online (Sandbox Code Playgroud)
我正在使用的数据是这样的数据框:
daily<-data.frame(type=c("A","A","B","C","C","C"),
d.happy=c(1,5,3,7,2,4),
d.sad=c(5,3,6,3,1,2))
Run Code Online (Sandbox Code Playgroud)
您可以在一个调用中执行此操作,方法是进行分组,使用mutate而不是summary,然后使用slice()保留每种类型的第一行:
daily %>% group_by(type) %>%
mutate(n = n()) %>%
mutate_at(vars(starts_with("d.")),funs(mean(., na.rm = TRUE))) %>%
slice(1L)
Run Code Online (Sandbox Code Playgroud)
编辑:在此修改的示例中,它可能更清楚如何工作
daily_summary <- daily %>% group_by(type) %>%
mutate(n = n()) %>%
mutate_at(vars(starts_with("d.")),funs("mean" = mean(., na.rm = TRUE)))
daily_summary
# Source: local data frame [6 x 6]
# Groups: type [3]
#
# # A tibble: 6 x 6
# type d.happy d.sad n d.happy_mean d.sad_mean
# <fctr> <dbl> <dbl> <int> <dbl> <dbl>
#1 A 1 5 2 3.000000 4
#2 A 5 3 2 3.000000 4
#3 B 3 6 1 3.000000 6
#4 C 7 3 3 4.333333 2
#5 C 2 1 3 4.333333 2
#6 C 4 2 3 4.333333 2
daily_summary %>%
slice(1L)
# Source: local data frame [3 x 6]
# Groups: type [3]
#
# # A tibble: 3 x 6
# type d.happy d.sad n d.happy_mean d.sad_mean
# <fctr> <dbl> <dbl> <int> <dbl> <dbl>
#1 A 1 5 2 3.000000 4
#2 B 3 6 1 3.000000 6
#3 C 7 3 3 4.333333 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
816 次 |
| 最近记录: |