0
votes

I have around 33 dataframes (df1, df2, df3, df4 ...) that look like this:

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

and I would like to group each data frame by month, like this:

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

How can I do this on all dataframes without repeating it? Also, I will need to export the results as separate data frames.

I've tried to duplicate some other people's solutions using for loop but doesn't work. Also, I have all the dataframes separately in my Environment, they are not in a list.

2

2 Answers

1
votes

You can get them in list using mget with your pattern, loop over them using lapply and then 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

Or if you want to use tidyverse

library(tidyverse)

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

To write them in separate csv's we can use mapply

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

data

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))
0
votes

We can use data.table methods

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