【问题标题】:Running for loop for multiple dataframes in R?在R中为多个数据帧运行for循环?
【发布时间】:2020-09-26 03:40:06
【问题描述】:

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

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

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

谢谢!

【问题讨论】:

  • 使用list-of-frames,然后使用updated_list_of_frames &lt;- lapply(list_of_frames, function(single_frame) ...)

标签: r for-loop


【解决方案1】:

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

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

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

list2env(new_data, .GlobalEnv)

【讨论】:

    【解决方案2】:

    另外两种方法。

    # 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.frames,使用双括号表示法 ([[):

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

    【讨论】:

      【解决方案3】:

      有了tidyverse,我们可以做到

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

      如果我们需要单独的数据集

      list2env(new_data, .GlobalEnv)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-22
        • 2021-07-05
        • 1970-01-01
        • 2019-11-23
        • 1970-01-01
        • 1970-01-01
        • 2022-01-16
        相关资源
        最近更新 更多