Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

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

I've the below dataframe with 10 columns.

V1  V2  V3  V4  V5  V6  V7  V8  V9  V10
1   2   3   4   5   6   7   8   9   10
11  12  13  14  15  16  17  18  19  20
21  22  23  24  25  26  27  28  29  30
31  32  33  34  35  36  37  38  39  40
41  42  43  44  45  46  47  48  49  50
51  52  53  54  55  56  57  58  59  60
61  62  63  64  65  66  67  68  69  70
71  72  73  74  75  76  77  78  79  80
81  82  83  84  85  86  87  88  89  90
91  92  93  94  95  96  97  98  99  100

I want to split that dataframe into different chunks with each two of its two columns as a new dataframe. For example, V1 & V2 into one dataframe, and V3 & V4 into one dataframe and so on:

V1  V2
1   2
11  12
21  22
31  32
41  42
51  52
61  62
71  72
81  82
91  92

V3  V4
3   4
13  14
23  24
33  34
43  44
53  54
63  64
73  74
83  84
93  94

How can I achieve this easily in R?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...