【问题标题】:Creating Subset data frames in R within For loop [duplicate]在 For 循环中的 R 中创建子集数据帧 [重复]
【发布时间】:2019-01-02 10:40:49
【问题描述】:

我要做的是根据较大数据帧中第一列的值将较大的数据帧过滤成 78 个唯一数据帧。我能想到的唯一方法是在 for() 循环中应用 filter() 函数:

 for (i in 1:nrow(plantline)) 
            {x1 = filter(rawdta.df, Plant_Line == plantline$Plant_Line[i])}

问题是我不知道如何在每次循环运行时创建一个新的数据框,比如 x2、x3、x4...。

有人可以告诉我这是否可能,或者我是否应该尝试以其他方式做到这一点?

【问题讨论】:

  • 你能给我们看一个plantline的例子吗?

标签: r


【解决方案1】:

你可以使用split -

# creates a list of dataframes into 78 unique data frames based on
# the value of the first column in the larger data frame
lst = split(large_data_frame, large_data_frame$first_column)

# takes the dataframes out of the list into the global environment
# although it is not suggested since it is difficult to work with 78 
# dataframes
list2env(lst, envir = .GlobalEnv)

数据框的名称将与第一列中变量的值相同。

【讨论】:

  • 为什么要从列表中取出数据框?只是让他们更难合作。
  • 我同意,但这就是 OP 的 for 循环所做的 - 将数据帧添加到全局环境中。为了完整起见,我还添加了它,以防以后有人查找此问题,并且拆分列中唯一值的数量要少得多,例如 3 或 4。
  • 我建议至少提及替代方案,而不是帮助新手在脚下开枪,因为那是他们正在尝试做的事情。
  • @Gregor,明白了。谢谢你。编辑是否使它变得更好?
  • 改进很多。对于阅读本文的任何人-使用for 循环或lapply(或Map 或许多其他选项...参见purrr 包)在list 中的每个数据帧上工作都很容易。然而,使用pasteassignget 以及其他黑客在您的环境中处理一堆几乎相同的数据帧更加困难且容易出错。我强烈建议将它们放在一个不错的列表中。
【解决方案2】:

使用plyr的解决方案:

ma <- cbind(x = 1:10, y = (-4:5)^2, z = 1:2)
ma <- as.data.frame(ma)

library(plyr)
dlply(ma, "z") # you split ma by the column named z

【讨论】:

    【解决方案3】:

    使用示例数据会更容易。 by 将是我的最爱。

    d <- data.frame(plantline = rep(LETTERS[1:3], 4),
                    x = 1:12, 
                    stringsAsFactors = F)
    
    l <- by(d, d$plantline, data.frame)
    
    print(l$A)
    print(l$B)
    

    【讨论】:

      【解决方案4】:

      这个问题一定有很多重复

      split(plantline, plantline$Plant_Line)
      

      将创建一个 data.frames 列表。

      但是,根据您的用例,可能不需要将大型 data.frame 拆分为多个部分,因为可以使用分组。

      【讨论】:

        【解决方案5】:

        你可以使用assign

        for (i in 1:nrow(plantline)) 
                {assign(paste0(x,i), filter(rawdta.df, Plant_Line == plantline$Plant_Line[i]))}
        

        或者,您可以将结果保存在 list 中:

        X <- list()    
        for (i in 1:nrow(plantline)) 
                {X[[i]] = filter(rawdta.df, Plant_Line == plantline$Plant_Line[i])}
        

        【讨论】:

        • fortunes::fortune(236) 唯一应该使用assign函数的人是那些完全理解为什么永远不应该使用assign函数的人。 -- Greg Snow R-help(7月2009)
        • 我不知道最佳实践,但感谢您向我介绍财富包!
        【解决方案6】:

        如果我们能看到数据框会更容易......

        尽管如此,我还是提出了一些建议。您可以创建数据框列表:

        dataframes <- vector("list", nrow(plantline))
        for (i in 1:nrow(plantline)){ 
             dataframes[[i]] = filter(rawdta.df, Plant_Line == plantline$Plant_Line[i])
        }
        

        【讨论】:

        • 谢谢!这正是我所需要的!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-05
        • 2015-06-20
        • 2017-07-27
        • 1970-01-01
        • 2020-05-01
        • 2022-11-22
        • 1970-01-01
        相关资源
        最近更新 更多