如何在R中一次创建数据帧(不仅是一个)

时间:2018-12-05 04:20:04

标签: r

这是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_iiplan中的行号的新数据帧。我尝试过

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的可能解决方案,但建议不要使用。非常感谢您的指教!

2 个答案:

答案 0 :(得分: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"]]等访问单个数据帧。

答案 1 :(得分:0)

您可以使用split使用您喜欢的因子将1个数据帧分成多个数据帧的列表。例如,以下内容将根据df列将id分成5个数据帧

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

如果您要使用data.frame的rownames代替id列,这也将起作用:

split(df, rownames(df))
相关问题