使用for循环对多个数据框应用更改(分组依据)

时间:2019-07-19 09:22:01

标签: r loops dataframe for-loop

我大约有33个数据帧(df1,df2,df3,df4 ...),如下所示:

Date       Month   Value  
2018-07-16 2018-07     10 
2018-07-17 2018-07     2
2018-07-18 2018-07     4 
2018-07-19 2018-07     45
2018-07-20 2018-07     13

,我想按月对每个数据帧进行分组,如下所示:

df1 = df1 %>% group_by(Month)%>%
  summarise(
    sd_value = sd(value)
  )

如何在所有数据帧上做到这一点而不重复? 另外,我需要将结果导出为单独的数据框。

我尝试使用for循环复制其他人的解决方案,但不起作用。 另外,我的环境中分别包含所有数据框,它们不在列表中。

2 个答案:

答案 0 :(得分:1)

您可以使用mget和您的模式将它们添加到列表中,使用lapply然后再使用aggregate遍历它们

list_name <- ls(pattern = "df\\d+")

list_df <- lapply(mget(list_name), function(x) aggregate(Value~Month, x, sd))
list_df

#$df1
#    Month    Value
#1 2018-07 17.45566

#$df2
#    Month    Value
#1 2018-07 185.8744

或者如果您想使用tidyverse

library(tidyverse)

list_df <- map(mget(list_name), 
          . %>% group_by(Month) %>% summarise(sd_value = sd(Value)))

要将它们写在单独的csv中,我们可以使用mapply

mapply(function(x, y) write.csv(x, 
      paste0("path/to/file/", y, ".csv"), row.names = FALSE), list_df, list_name)

数据

df1 <- structure(list(Date = structure(1:5, .Label = c("2018-07-16", 
"2018-07-17", "2018-07-18", "2018-07-19", "2018-07-20"), class = "factor"), 
Month = structure(c(1L, 1L, 1L, 1L, 1L), .Label = "2018-07", class = "factor"), 
Value = c(10L, 2L, 4L, 45L, 13L)), class = "data.frame", row.names = 
c(NA, -5L))

df2 <- structure(list(Date = structure(1:5, .Label = c("2018-07-16", 
 "2018-07-17", "2018-07-18", "2018-07-19", "2018-07-20"), class = "factor"), 
Month = structure(c(1L, 1L, 1L, 1L, 1L), .Label = "2018-07", class = "factor"), 
Value = c(11L, 2L, 4L, 423L, 13L)), class = "data.frame", row.names = 
c(NA, -5L))

答案 1 :(得分:0)

我们可以使用data.table方法

library(data.table)
lapply(mget(ls(pattern = "df\\d+")), function(x)
            setDT(x)[, .(sd_value = sd(Value)), by = Month])