0

I have a data frame with 3 columns, for example:

my.data <- data.frame(A=c(1:5), B=c(6:10), C=c(11:15))

I would like to split each column into its own data frame (so I'd end up with a list containing three data frames). I tried to use the "split" function but I don't know what I would set as the factor argument. I tried this:

data.split <- split(my.data, my.data[,1:3])

but that's definitely wrong and just gives me a bunch of empty data frames. It sounds fairly simple but after searching through previous questions I haven't come across a way to do this.

2 Answers2

2

Not sure why you'd want to do that; lapply let's you already operate on the columns directly; but you could do

lst <- split(t(my.data), 1:3);
names(lst) <- names(my.data);
lst;
#$A
#[1] 1 2 3 4 5
#
#$B
#[1]  6  7  8  9 10
#
#$C
#[1] 11 12 13 14 15

Turn vector entries into data.frames with

lapply(lst, as.data.frame);
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
2

You can use split.default, i.e.

split.default(my.data, seq_along(my.data))


$`1`
  A
1 1
2 2
3 3
4 4
5 5

$`2`
   B
1  6
2  7
3  8
4  9
5 10

$`3`
   C
1 11
2 12
3 13
4 14
5 15
Sotos
  • 51,121
  • 6
  • 32
  • 66