每两列将数据框拆分为多个数据框 [英] Split dataframe every two columns into multiple dataframe

查看:49
本文介绍了每两列将数据框拆分为多个数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个数据框,其中包含未知数(和可变数)的列(总是2的倍数).该文件的标题如下所示:

I have multiple data-frames containing an unknown (and variable) number of columns (always a multiple of 2). Headers of the file look like that:

X0, Y0, X1, Y1, X2, Y2 ... Xn, Yn

每个成对的列包含相同的行数,但非成对的列之间的行数不同.

Each of the paired columns contains the same number of row, but the number of row is different between non-paired column.

使用R,我想将这些数据帧切成多个仅包含成对列的小帧:

Using R, I would like to slit these data-frames in multiple small one that contain only the paired column:

X0, Y0, X1, Y1, X2, Y2,... Xn, Yn

进入:

X0, Y0
X1, Y1
X2, Y2

以此类推.

我试图建立循环,但到目前为止没有成功.

I tried to set up loops but without success so far.

有人可以指出正确的方向/方法来解决这个问题吗?

Could anyone point me in the right direction / approach to solve this ?

非常感谢.

推荐答案

lapply(seq(1, ncol(df), by=2), function(i) 
     df[i: pmin((i+1), ncol(df))])

[[1]]
  X0 Y0
1  1  2
2 11 12
3 21 22
4 31 32
5 41 42

[[2]]
  X1 Y1
1  3  4
2 13 14
3 23 24
4 33 34
5 43 44

[[3]]
  X2 Y2
1  5  6
2 15 16
3 25 26
4 35 36
5 45 46

[[4]]
  X3 Y3
1  7  8
2 17 18
3 27 28
4 37 38
5 47 48

[[5]]
  X4 Y4
1  9 10
2 19 20
3 29 30
4 39 40
5 49 50

数据:

dput(df)
structure(list(X0 = c(1L, 11L, 21L, 31L, 41L), Y0 = c(2L, 12L, 
22L, 32L, 42L), X1 = c(3L, 13L, 23L, 33L, 43L), Y1 = c(4L, 14L, 
24L, 34L, 44L), X2 = c(5L, 15L, 25L, 35L, 45L), Y2 = c(6L, 16L, 
26L, 36L, 46L), X3 = c(7L, 17L, 27L, 37L, 47L), Y3 = c(8L, 18L, 
28L, 38L, 48L), X4 = c(9L, 19L, 29L, 39L, 49L), Y4 = c(10L, 20L, 
30L, 40L, 50L)), .Names = c("X0", "Y0", "X1", "Y1", "X2", "Y2", 
"X3", "Y3", "X4", "Y4"), class = "data.frame", row.names = c(NA, 
-5L))

这篇关于每两列将数据框拆分为多个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆