正在为R中的多个数据帧运行循环?

问题描述 投票:1回答:3

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

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

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

谢谢!

r for-loop
3个回答
2
投票

如果数据框称为df1df2等,则可以使用此模式使用mget获取列表中的数据框,并使用transform在每个数据框中添加新列。

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

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

list2env(new_data, .GlobalEnv)

0
投票

另外两种方法。

# create example data
df1 <- df2 <- data.frame(x=1:4, y=1:4)

# put into a list
l <- list(df1, df2)

# iterate over the list with a for loop
for(i in 1:length(l)){
  l[[i]]$new_column <- l[[i]]$x + l[[i]]$y
}

# same as above, but using `lapply()` and an anonymous function
# this requires you have the package `dplyr`
lapply(l, function(j) dplyr::mutate(j, new_column = x + y))

都返回:

[[1]]
  x y new_column
1 1 1          2
2 2 2          4
3 3 3          6
4 4 4          8

[[2]]
  x y new_column
1 1 1          2
2 2 2          4
3 3 3          6
4 4 4          8

并且如上所述,要访问各个列表元素,在本示例中我们将其设为data.frame,请使用双括号符号([[):

> l[[1]]
  x y new_column
1 1 1          2
2 2 2          4
3 3 3          6
4 4 4          8

0
投票

使用tidyverse,我们可以做

library(dplyr)
library(purrr)
new_data <- lmget(ls(pattern = '^df\\d+$')) %>%
        map(~ .x %>%
                  mutate(newcolumn = a + b + c))

如果需要单独的数据集

list2env(new_data, .GlobalEnv)
© www.soinside.com 2019 - 2024. All rights reserved.