Using lapply on a list of data frames

25 views
Skip to first unread message

Sharon Dabach

unread,
Oct 1, 2015, 12:55:15 PM10/1/15
to Davis R Users' Group
Hi all,

I have a list of some data frames (attached). the name of each element of the list is the date in which the measurements were taken. I also have a vector of the dates called "waf_dates"
I want to summarize each data frame and write the results to one new data frame.
I tried to do that with lapply like this:
library(dplyr)
library(lubridate)
ttl_emsn <- lapply (waf_files, sum_fun)

sum_fun <- function (waf) {
  waf %>%
    group_by (treat) %>%
    summarise (date = ymd (names(waf)),
               emission = round (sum (n2o*collar_area), digits = 2), # calculates total flux per treatment
               emission_err = round (sqrt (sum ((emsn_err)), digits = 2))
               )
  }
The problem seems to be with assigning the names to the date column "date = ymd (names(waf))"

So I tried to do that with a for loop:
for (i in seq_along (waf_files)) {
  ttl_emssn <- waf_files [[i]] %>%
    group_by (treat) %>%
    summarise (date = ymd (waf_dates [i]),
               emission = round (sum (n2o*collar_area), digits = 2),
               emssn_err = round (sqrt (sum (emission_err)), digits = 2)
               )
}
This solved the date issue but only wrote the summary of the last element of the list.
When I tried to index ttl_emssn like this :
ttl_emssn [i*3-2,] the whole thing got crazy

Can someone help? 



Sharon Dabach

unread,
Oct 1, 2015, 12:56:59 PM10/1/15
to Davis R Users' Group
Oops 
Here are the files
waf_dates.RDS
waf_files.RDS

Jaime Ashander

unread,
Oct 1, 2015, 1:16:40 PM10/1/15
to davi...@googlegroups.com
Hi, 
The issues is names(war) gives you all the names of the data frame within the list, not the date character string which you wanted.

Here's a fix:

readRDS('waf_files.RDS') -> waf_files
# dates are the same as names(waf_files) so omit them

library(dplyr)
library(lubridate)

sum_fun <- function (date) {
  waf_files[[date]] %>%
    group_by (treat) %>%
    summarise (date = ymd (date),
               emission = round (sum (n2o*collar_area), digits = 2),
               emssn_err = round (sqrt (sum (emission_err)), digits = 2)
    )
}

ttl_emsn <- lapply (names(waf_files), sum_fun)
emission_summary <- do.call(rbind, ttl_emsn)
emission_summary
> --
> Check out our R resources at http://www.noamross.net/davis-r-users-group.html
> ---
> You received this message because you are subscribed to the Google Groups "Davis R Users' Group" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to davis-rug+...@googlegroups.com.
> Visit this group at http://groups.google.com/group/davis-rug.
> For more options, visit https://groups.google.com/d/optout.

Sharon Dabach

unread,
Oct 1, 2015, 1:50:44 PM10/1/15
to Davis R Users' Group
Thanks!
Works now
Reply all
Reply to author
Forward
0 new messages