Search code examples
rvariablesoperation

R - How to perform the same operation on multiple variables


In R, I often times need to do the same operation for a group of variables.

As an example, on my environment I currently have the following of data frames:

df_model1
df_model2
df_model3
df_model4
df_model5

and I have another data frame called df_obs.

What I need to do is to merge each of the df-model* data frame to df_obs.

What I usually do is something like this:

new_df_model1 <- merge(df_obs, df_model1, all=TRUE)
new_df_model2 <- merge(df_obs, df_model2, all=TRUE)
...

and so on, which is clearly not very practical.

How can I make this operation more programmatic?


Solution

  • You could use Map to merge df_obs and the df_model datasets in a list.

     lst <- Map(`merge`, list(df_obs), 
              mget(paste0('df_model', 1:5)), MoreArgs=list(all=TRUE))
    

    If the output datasets in the list needs to be separate data.frame objects in the global environment, we can use list2env (but I would prefer to keep it in the list as most of the operations can be done within the list)

     names(lst) <- paste('new',paste0('df_model', 1:5), sep="_")
     list2env(lst, envir= .GlobalEnv)
    

    Or using lapply

     lapply(mget(paste0('df_model', 1:5)), merge, x = df_obs, all=TRUE)