I have created like ten different data frames (eg. df1, df2, ..., df10). I want to use the function "spread" in R on all these data frames. My solution is to create a function in R that can repeat the function "spread" on all the data frames and create ten new data frames with the updated name: df1_wide, df2_wide, ..., df10_wide. My initial idea is something like this:
new_function <- function(df) {
"df"_wide <- spread(df, key=time, value=values)
}
df_list <- list(df1,df2,...,df10)
function(df_list)
Unfortunately, it does not work.
CodePudding user response:
spread
has been retired so you may switch to pivot_wider
. Use lapply
to apply the custom function to each dataframe in the list.
new_function <- function(df) {
tidyr::pivot_wider(df, names_from =time, values_from =values)
}
df_list <- list(df1,df2,...,df10)
#Or
#df_list <- mget(paste0('df', 1:10))
df_result <- lapply(df_list, new_function)