在R中为多个数据帧运行循环吗? [英] Running for loop for multiple dataframes in R?

查看:67
本文介绍了在R中为多个数据帧运行循环吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有多个数据帧,并且我正在尝试计算特定列的总和并存储在每个EACH数据帧的数据帧中的新列中,我不确定该怎么做.到目前为止,我可以为单个数据帧运行一个for循环:

So I have multiple data frames and I'm trying to calculate the sum of specific columns and store within a new column in the data frame for EACH data frame and I'm not sure how to go about it. So far, I can run a for loop for a single dataframe:

for (i in nrow(df1)){df1$newcolumn <-(df1$a + df1$b + df1$c)}

但是,如果我有多个数据帧(df1,df2,df3 ...),该怎么做?每个数据框的列名都相同.

But if I have multiple data frames (df1,df2,df3,...), how do I do this? The column names are the same for each dataframe.

谢谢!

推荐答案

如果您的数据框名为 df1 df2 等,则可以使用此模式获取数据框使用 mget 创建一个列表,然后使用 transform 在每个数据框中添加一个新列.

If your dataframe is called df1, df2 etc, you can use this pattern to get dataframe in a list using mget and add a new column in each dataframe using transform.

new_data <- lapply(mget(ls(pattern = 'df\\d+')), function(df) 
                   transform(df, newcolumn = a + b + c))

这将返回数据帧列表,如果您希望将它们作为单个数据帧再次使用 list2env .

This will return list of dataframes, if you want them as individual dataframes again use list2env.

list2env(new_data, .GlobalEnv)

这篇关于在R中为多个数据帧运行循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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