[英]Append observation at end of row from another column in R
I have data with 900 rows and 400 columns. 我有900行400列的数据。 Each two column carry particular information.
每两列携带特定信息。 Let me say, there are ABCD column, I will like append C and C column just end of A and B column.
我说,有ABCD列,我想在A和B列的末尾追加C和C列。
For example: 例如:
A B C D E F
3 4 5 6 7 8
9 10 11 12 13 14
to change to 更改为
Column 1 Column 2
3 4
9 10
5 6
11 12
7 8
13 14
You could create the new data.frame
by stacking the odd and even columns of the original df
into 2 new columns. 您可以通过将原始
df
的奇数和偶数列堆叠到2个新列中来创建新的data.frame
。
df1 <- data.frame(Column1 = unlist(df[,c(T,F)]),
Column2 = unlist(df[,c(F,T)]))
> df1
# Column1 Column2
#A1 3 4
#A2 9 10
#C1 5 6
#C2 11 12
#E1 7 8
#E2 13 14
Assuming o
is all numeric, convert to a matrix: 假设
o
都是数字,则转换为矩阵:
o <- read.table(text='A B C D E F
3 4 5 6 7 8
9 10 11 12 13 14', header=TRUE)
o <- as.matrix(o)
First, you actually have pairs of columns, so this could be thought of as a 3D array. 首先,您实际上有成对的列,因此可以将其视为3D数组。 We can reshape to 3d in-place:
我们可以就地重塑为3d:
dim(o) <- c(2,2,3)
So o
looks like this: 所以
o
看起来像这样:
> o
, , 1
[,1] [,2]
[1,] 3 4
[2,] 9 10
, , 2
[,1] [,2]
[1,] 5 6
[2,] 11 12
, , 3
[,1] [,2]
[1,] 7 8
[2,] 13 14
Using aperm to move the indices, and dim<-
to reshape, we can get pretty close: 使用aperm移动索引,并使用
dim<-
重塑形状,我们可以非常接近:
>`dim<-`(aperm(o, c(3,1,2)), c(6,2))
[,1] [,2]
[1,] 3 4
[2,] 5 6
[3,] 7 8
[4,] 9 10
[5,] 11 12
[6,] 13 14
If you actually want it in exactly the 2d order above you need a transpose: 如果您实际上确实想要上面的2d顺序,则需要转置:
> t(`dim<-`(aperm(o, c(2,1,3)), c(2,6)))
[,1] [,2]
[1,] 3 4
[2,] 9 10
[3,] 5 6
[4,] 11 12
[5,] 7 8
[6,] 13 14
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.