R - How to perform the same operation on multiple variables

血红的双手。 提交于 2019-12-24 04:46:08

问题


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?


回答1:


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)



回答2:


You could use a for loop

for(i in 1:5) {
  data <- paste("new_df_model", i, sep = "")
  model <- merge(df_obs, paste("df_model", i, sep = ""), all = TRUE)
  assign(data, model)
}


来源:https://stackoverflow.com/questions/30274459/r-how-to-perform-the-same-operation-on-multiple-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!