lapply
Using lapply to apply a function over list of data frames and saving output to files with different names
It will work with the following lapply call: lapply(names(mylist), function(x) NewVar(mylist[[x]], “y”, x))
Writing multiple data frames into .csv files using R
Here’s a self-contained example along the lines of Richard’s comment, but uses the names of the dataframes in the list as filenames for the CSV files: # Create a list of n data frames n <- 10 my_list <- lapply(1:n, function(i) data.frame(x = rnorm(10), y = rnorm(10)) ) # name the data frames names(my_list) <- … Read more
Add “filename” column to table as multiple files are read and bound
I generally use the following approach, based on dplyr/tidyr: data = tibble(File = files) %>% extract(File, “Site”, “([A-Z]{2}-[A-Za-z0-9]{3})”, remove = FALSE) %>% mutate(Data = lapply(File, read_csv)) %>% unnest(Data) %>% select(-File)
How to tell lapply to ignore an error and process the next thing in the list?
Use a tryCatch expression around the function that can throw the error message: testFunction <- function (date_in) { return(tryCatch(as.Date(date_in), error=function(e) NULL)) } The nice thing about the tryCatch function is that you can decide what to do in the case of an error (in this case, return NULL). > lapply(dates2, testFunction) [[1]] [1] “2010-04-06” [[2]] … Read more
What are the performance differences between for-loops and the apply family of functions?
First of all, it is an already long debunked myth that for loops are any slower than lapply. The for loops in R have been made a lot more performant and are currently at least as fast as lapply. That said, you have to rethink your use of lapply here. Your implementation demands assigning to … Read more
lapply-ing with the “$” function
This is documented in ?lapply, in the “Note” section (emphasis mine): For historical reasons, the calls created by lapply are unevaluated, and code has been written (e.g. bquote) that relies on this. This means that the recorded call is always of the form FUN(X[[0L]], …), with 0L replaced by the current integer index. This is … Read more
How to index an element of a list object in R
Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes … Read more