0
votes

I have the same problem as this guy: returning from list to data.frame after lapply

Whilst they solved his specific problem, no one actually answered his original question about how to get dataframes out of a list.

I have a list of data frames:

dfPreList = list(yearlyFunding, yearlyPubs, yearlyAuthors)

And I want to filter/replace etc on them all.

So my function is:

DoThis = function(x){
  filter(x, year >=2015 & year <=2018) %>% 
  replace(is.na(.), 0) %>%
  adorn_totals("row")

}

And I use lapply to run the function on them all like this:

a = lapply(dfPreList, DoThis) 

As the other post stated, these data frames are now stuck in this list (a), and I need a for loop to get them out, which just cannot be the correct way of doing it.

This is my current working way of applying the function to the dataframes and then getting them out:

dfPreList = list(yearlyFunding, yearlyPubs, yearlyAuthors)
dfPreListstr= list('yearlyFunding', 'yearlyPubs', 'yearlyAuthors')

DoThis = function(x){
  filter(x, year >=2015 & year <=2018) %>% 
  replace(is.na(.), 0) %>%
  adorn_totals("row")

}

a = lapply(dfPreList, DoThis)

for( i in seq_along(dfPreList)){

  assign(dfPreListstr[[i]], as.data.frame(a[i]))

}

Is there a way of doing this without having to rely on for loops and string names of the dataframes? I.e. a one-liner with the lapply?

Many thanks for your help

2

2 Answers

2
votes

You can assign names to the list and then use list2env.

dfPreList = list(yearlyFunding, yearlyPubs, yearlyAuthors)
a = lapply(dfPreList, DoThis) 
names(a) <- c('yearlyFunding', 'yearlyPubs', 'yearlyAuthors')
list2env(a, .GlobalEnv)
1
votes

Another way would be to unlist the list, then convert the content into data frame.

dfPreList = list(yearlyFunding, yearlyPubs, yearlyAuthors)
a = lapply(dfPreList, DoThis)
names(a) <- c('yearlyFunding', 'yearlyPubs', 'yearlyAuthors')

yearlyFunding <- data.frame(matrix(unlist(a$yearlyFunding), nrow= nrow(yearlyFunding), ncol= ncol(yearlyFunding)))
yearlyPubs <- data.frame(matrix(unlist(a$yearlyPubs), nrow= nrow(yearlyPubs), ncol= ncol(yearlyPubs)))
yearlyAuthors <- data.frame(matrix(unlist(a$yearlyAuthors), nrow= nrow(yearlyAuthors), ncol= ncol(yearlyAuthors)))

Since unlist function returns a vector, we first generate a matrix, then convert it to data frame.