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