Home > Mobile >  Looping through data frames in global environment and passing a function to all to create new list
Looping through data frames in global environment and passing a function to all to create new list

Time:03-10

I have 125 89x89 dataframes in my global environment and need to turn each into a into 1 x 7921 (i.e., 89^2) dataframe and then bind them into a single 125 x 7921 DataFrame. I'm having success getting the dataframes from independent objects in the global environment into a list using mget:

For example,

dfs_list <- Filter(function(x) is(x, "data.frame"), mget(ls()))

returns a list of 125 89x89 dataframes in df_list.

Where I might be messing up and where I've struggled the most is writing a function for the lapply call. I'm trying to use

list1 <- lapply(mget(ls()), f1)

where f1 is the function I need to call to transform the data from long to wide for each DataFrame.

The function I am trying to use is

f1 <- function(data.frame) {
   . %>%
   dplyr::mutate(dplyr::mutate(row = row_number()) %>% 
   tidyr::pivot_wider(names_from = row, values_from = -row)
}

which stems from a previous question I asked here. The code within the function works perfectly when I pass just one DataFrame at a time, but seeing as this is a large dataset that is going to continue to expand and need to be pivoted, it would be nice to have a function to automate the process.

The output of running list1 <- lapply(mget(ls()), f1) on the objects in my global environment is a list of 125 functions. What I am trying to get is an output list length of 125 with the wide dataframes.

Thanks for any help.

CodePudding user response:

I've figured out the issue was with my function f1 and mget(ls()) in lapply. Here's what worked to solve the problem:

A

dfs_list <- Filter(function(x) is(x, "data.frame"), mget(ls()))

B

f1 <- function(df) { 
   df %>% 
     dplyr::mutate(dplyr::mutate(row = row_number()) %>% 
     tidyr::pivot_wider(names_from = row, values_from = -row)
}

C

lst1 <- lapply(dfs_list, f1)
  • Related