2

Given a dataframe

A <- c("One", "Two", "Three")
B <- c(1,2,3)
C <- c(1,1,1)
df <- data.frame(A,B,C)

I would like to generate a list of dataframe such that it looks like the example below

A
One
Two
Three

A     B
One   1
Two   2
Three 3 

A     B  C
One   1  1
Two   2  1
Three 3  1

I'am dealing with a dataframe with ~50 columns. I tried several attemps but with little success.

Thanks!

MoorZ
  • 33
  • 4
  • This should do the trick: https://stackoverflow.com/questions/45628665/how-to-select-a-particular-dataframe-from-a-list-of-dataframes-in-python-equival/45639343#45639343 – vestland Oct 21 '17 at 13:09

2 Answers2

1

We can use saaply to select incremental columns using seq.

sapply(seq(ncol(df)), function(x) df[seq(x)])

#[[1]]
#      A
#1   One
#2   Two
#3 Three

#[[2]]
#      A B
#1   One 1
#2   Two 2
#3 Three 3

#[[3]]
#      A B C
#1   One 1 1
#2   Two 2 1
#3 Three 3 1
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • But he has 50 columns already to create df first. So that would be time consuming first to make df. Good use of `seq()` though – Sowmya S. Manian Oct 21 '17 at 13:13
  • 1
    @SowmyaS.Manian I tried it with 50 columns dataframe. It doesn't even take a second. Could you check it at your end and confirm the timing? – Ronak Shah Oct 21 '17 at 13:18
  • Yeah all kool. Working Good. Were you able to find it incrementally as in 1 to no. of vectors in the list appending one by one and then to list? – Sowmya S. Manian Oct 21 '17 at 13:25
  • Sorry, didn't get you. What do you mean by `find it` ? what is `it` here? – Ronak Shah Oct 21 '17 at 13:33
0

You can use a standard loop like so:

A <- c("One", "Two", "Three")
B <- c(1,2,3)
C <- c(1,1,1)
df <- data.frame(A,B,C)

dfList = list()
for(i in 1:ncol(df)){


  dfSub <- data.frame(df[,1:i])
  dfList[[i]] <- dfSub

  }


dfList
[[1]]
  df...1.i.
1       One
2       Two
3     Three

[[2]]
      A B
1   One 1
2   Two 2
3 Three 3

[[3]]
      A B C
1   One 1 1
2   Two 2 1
3 Three 3 1
DataTx
  • 1,839
  • 3
  • 26
  • 49