【问题标题】:how to create data frames (not just one) at once in r如何在 r 中一次创建数据帧(不仅仅是一个)
【发布时间】:2018-12-05 04:20:04
【问题描述】:

这是来自unordered combination and store the result in a matrix in r 的另一个问题。

现在我有一个如下的数据框

>head(plan)
  bal midway coro cab ljc ot
1   1      1    1   2   2  2
2   1      1    2   1   1  2
3   1      1    2   1   2  2
4   1      1    2   2   1  2
5   1      1    2   2   2  1
6   1      2    1   1   2  2

我想提取每行中等于 1 的元素,使用其列名并排列它们,以存储在新的数据框中,例如第一行的 day_1_1

> permutations(3, 3, v = names(plan)[which(plan[1,] == 1, arr.ind=T)[, "col"]])
     [,1]     [,2]     [,3]    
[1,] "bal"    "coro"   "midway"
[2,] "bal"    "midway" "coro"  
[3,] "coro"   "bal"    "midway"
[4,] "coro"   "midway" "bal"   
[5,] "midway" "bal"    "coro"  
[6,] "midway" "coro"   "bal"  

我的问题是我不知道如何在循环中创建那些名为day_1_ii 匹配plan 中的行号)的新数据框。我试过了

for (i in 1:nrow(plan)) {
  paste0("day_1_", i) <- permutations(3, 3, v = names(plan)[which(plan[i,] == 1, arr.ind=T)[, "col"]])
}

但它不起作用。我从Using a loop to create multiple data frames in R 看到了一种使用assign 的可能解决方案,但建议不要使用。非常感谢您的建议!

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以将其存储在数据框列表中

    library(gtools)
    
    list_df <- list()
    for (i in 1:nrow(plan)) {
       list_df[[i]] <- data.frame(permutations(3, 3, 
               v = names(plan)[which(plan[i,] == 1, arr.ind=T)[, "col"]]))
    }
    

    然后,如果您需要,您可以将其重命名为您的选择

    list_df <- setNames(list_df, paste0("day_1_", 1:nrow(plan)))
    
    list_df
    #$day_1_1
    #      X1     X2     X3
    #1    bal   coro midway
    #2    bal midway   coro
    #3   coro    bal midway
    #4   coro midway    bal
    #5 midway    bal   coro
    #6 midway   coro    bal
    
    #$day_1_2
    #   X1  X2  X3
    #1 bal cab ljc
    #2 bal ljc cab
    #3 cab bal ljc
    #4 cab ljc bal
    #5 ljc bal cab
    #6 ljc cab bal
    #....
    #....
    

    因此,您现在可以按名称 list_df[["day_1_1"]]list_df[["day_1_2"]] 等访问各个数据帧。

    【讨论】:

    • 这样更好。谢谢!
    【解决方案2】:

    您可以使用split 使用您喜欢的因素将 1 个数据框拆分为多个数据框的列表。比如下面会根据id列将df拆分成5个数据框

    df <- data.frame(id = 1:5, Val = rnorm(5))
    split(df, df$id)
    

    如果您想使用 data.frame 的 rownames 而不是 id 列,这也将起作用:

    split(df, rownames(df))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      相关资源
      最近更新 更多