2

This is a further question from unordered combination and store the result in a matrix in r.

Now I have a data frame as below

>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

I want to extract elements in each row which are equal to 1, use its column name and permutate them, to store in a new data frame, say day_1_1 for the first row:

> 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"  

My problem is I don't know how to create those new data frame called day_1_i (i matches the row number in plan) in a loop. I've tried

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

But it doesn't work. I've seen one possible solution using assign from Using a loop to create multiple data frames in R, but it's suggested to not use. Thanks a lot for advise!

vincent
  • 307
  • 1
  • 2
  • 11

2 Answers2

1

You can store it in a list of dataframes instead

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"]]))
}

and then if you need you can rename it to your choice

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
#....
#....

So you can now access individual dataframes by name list_df[["day_1_1"]] , list_df[["day_1_2"]] and so on.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

You can use split to split 1 data frame into a list of multiple data frames using a factor you like. For example, the following will split df into 5 data frames based on the id column

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

This will also work if you want to use rownames of the data.frame instead of and id column:

split(df, rownames(df))
Jozef
  • 2,617
  • 14
  • 19