QAsena
QAsena

Reputation: 641

Append columns to list of dataframes using lapply and mapply

I have a list of dataframes that to manipulate individually that looks like this:

df_list <- list(A1 = data.frame(v1 = 1:10,
                                v2 = 11:20),
                A2 = data.frame(v1 = 21:30,
                                v2 = 31:40))
df_list

Using lapply allows me to run a function over the list of dataframes like this:

library(tidyverse)
some_func <- function(lizt, comp = 2){
  lizt <- lapply(lizt, function(x){
    x <- x %>%
      mutate(IMPORTANT_v3 = v2 + comp)
    return(x)
  })
}
df_list_1 <- some_func(df_list)
df_list_1

So far so good but I need to run the function multiple times with different arguments so using mapply returns:

df_list_2 <- mapply(some_func,
                    comp = c(2, 3, 4),
                    MoreArgs = list(
                      lizt = df_list
                      ),
                    SIMPLIFY = F
)
df_list_2

This creates a new list of dataframes for each argument fed to the function in mapply giving me 3 lists of 2 dataframes. This is good but the output I'm looking for is to append a new column to each original dataframe for each argument in the mapply that would look like this:

desired_df_list <- list(A1 = data.frame(v1 = 1:10,
                                        v2 = 11:20,
                                        IMPORTANT_v3 = 13:22,
                                        IMPORTANT_v4 = 14:23,
                                        IMPORTANT_v5 = 15:24),
                        A2 = data.frame(v1 = 21:30,
                                        v2 = 31:40,
                                        IMPORTANT_v3 = 33:42,
                                        IMPORTANT_v4 = 34:43,
                                        IMPORTANT_v5 = 35:44))
desired_df_list

How can I wrangle the output of lists of lists of dataframes to isolate and append only the desired new columns (IMPORTANT_v3) to the original dataframe? Also open to other options such as mutating multiple columns inside the lapply using mapply but I haven't figured out how to code that as yet. Thanks!

Upvotes: 0

Views: 178

Answers (1)

QAsena
QAsena

Reputation: 641

Solved like this:

main_func <- function(lizt, comp = c(2:4)){
  lizt <- lapply(lizt, function(x){

    df <- mapply(movavg,
                 n = comp,
                 type = "w",
                 MoreArgs = list(x$v2),
                 SIMPLIFY = T
    )
    colnames(df) <- paste0("IMPORTANT_v", 1:ncol(df))
    print(df)
    print(x)
    x <- cbind(x, df)
    return(x)
  })

}
desired_df_list_complete <- main_func(df_list)
desired_df_list_complete

using movavg from pracma package in this example.

Upvotes: 0

Related Questions