我有2个变量需要总结,而且我很难在R中循环。我想按年对变量进行分组,然后汇总两个变量:R_D$
和Returns$
。我的代码如下......如何进行循环而不是两次编写代码?
R_DYear<- df %>% group_by(Year) %>%
do(data.frame(as.list(summary(.$`R_D$`)), check.names = FALSE))
ds2 <-df %>%
group_by(Year) %>%
summarise( sum=sum(`R_D$`), sd=sd(`R_D$`))
R_DYear<- R_DYear%>% left_join(ds2)
Returs_Year<- df %>% group_by(Year) %>%
do(data.frame(as.list(summary(.$`Returns$`)), check.names = FALSE))
ds3 <-df %>%
group_by(Year) %>%
summarise( sum=sum(`Returns$`), sd=sd(`Returns$`))
Returs_Year<- Returs_Year %>% left_join(ds3)
Year Min. 1st Qu. Median Mean 3rd Qu. Max. sum sd
2006 0 0.0 1.2 15.5 16.0 161.0 730.2 31.6
2007 0 0.0 0.9 20.8 18.1 213.9 976.2 45.0
2008 0 0.0 2.2 30.2 20.1 361.4 1418.6 72.9