How to split a data frame into multiple dataframes with each two columns as a new dataframe?

Try tapply with an INDEX argument of 1, 1, 2, 2, etc.

tapply(as.list(DF), gl(ncol(DF)/2, 2), as.data.frame)

giving (continued below output):

$`1`
   V1 V2
1   1  2
2  11 12
3  21 22
4  31 32
5  41 42
6  51 52
7  61 62
8  71 72
9  81 82
10 91 92

$`2`
   V3 V4
1   3  4
2  13 14
3  23 24
4  33 34
5  43 44
6  53 54
7  63 64
8  73 74
9  83 84
10 93 94

$`3`
   V5 V6
1   5  6
2  15 16
3  25 26
4  35 36
5  45 46
6  55 56
7  65 66
8  75 76
9  85 86
10 95 96

$`4`
   V7 V8
1   7  8
2  17 18
3  27 28
4  37 38
5  47 48
6  57 58
7  67 68
8  77 78
9  87 88
10 97 98

Another possibility if there is an all numeric data frame as in the question is to reshape it into an array:

a <- array(unlist(DF), c(nrow(DF), 2, ncol(DF)/2))

in which case a[,,i] is the ith matrix for i = 1, …, ncol(DF)/2 .

Note: The input DF in reproducible form is:

DF <- as.data.frame(matrix(1:100, 10, byrow = TRUE))

Leave a Comment