R-如何对多个变量执行相同的操作 [英] R - How to perform the same operation on multiple variables

查看:132
本文介绍了R-如何对多个变量执行相同的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中,我经常需要对一组变量执行相同的操作.

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

还有另一个名为df_obs的数据框.

and I have another data frame called df_obs.

我需要做的是将每个df-model*数据帧合并到df_obs.

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

我通常要做的是这样:

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?

推荐答案

您可以使用Mapmerge df_obslist中的df_model数据集.

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))

如果在全局环境中列表中的输出数据集需要是单独的data.frame对象,我们可以使用list2env(但我宁愿将其保留在列表中,因为大多数操作都可以在列表)

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)

或使用lapply

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

这篇关于R-如何对多个变量执行相同的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆