2

Let I have such a data frame(df);

col1  col2  col3  col4  col5  col6
12    15    21    19    45    43
37    77    90    4     0     51

Namely;

df<-data.frame(col1=c(12,37),col2=c(15,77),col3=c(21,90),col4=c(19,4),col5=c(45,0),col6=c(43,51))

I want to split df into groups and compose a list with these groups. For example, let split df into 2 equal parts

df1:

col1  col2  col3  
12    15    21   
37    77    90   

df2:

col4  col5  col6
19    45    43
4     0     51

And compose a list:

List[1]:

df1

List[2]:

df2

The main aim is to compose the list. However, the number of splitted data frames can change. How can I do this with R? I will be very glad with any help. Thanks a lot.

oercim
  • 1,808
  • 2
  • 17
  • 34

2 Answers2

3

Here's another similar approach

We can define an helper function that will split the data set according to a given n

splitdf <- function(df, n) {
  indx <- matrix(seq_len(ncol(df)), ncol = n)
  lapply(seq_len(n), function(x) df[, indx[, x]])
}

Then you can play around with different ns

splitdf(df, 3)
# [[1]]
# col1 col2
# 1   12   15
# 2   37   77
# 
# [[2]]
# col3 col4
# 1   21   19
# 2   90    4
# 
# [[3]]
# col5 col6
# 1   45   43
# 2    0   51

Or

splitdf(df, 2)
# [[1]]
# col1 col2 col3
# 1   12   15   21
# 2   37   77   90
# 
# [[2]]
# col4 col5 col6
# 1   19   45   43
# 2    4    0   51

Or

splitdf(df, 1)
# [[1]]
# col1 col2 col3 col4 col5 col6
# 1   12   15   21   19   45   43
# 2   37   77   90    4    0   51
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
1

One option using split to split the columns and lapply to subset::

lapply(split(colnames(df),rep(c(1,2),each=ncol(df)/2)),
+        function(x)df[x])
$`1`
  col1 col2 col3
1   12   15   21
2   37   77   90

$`2`
  col4 col5 col6
1   19   45   43
2    4    0   51

It is generally easier to split data.frame by rows, so you can use just split. Here you can also for fun do the same thing using the transpose:

 lapply(split(as.data.frame(t(df)),rep(c(1,2),each=ncol(df)/2)),t)
agstudy
  • 119,832
  • 17
  • 199
  • 261