[英]How can I transpose every nth (9th) column to a new row in R?
I found some similar questions but not based on R programming or not based on transposition based on the number of columns.我发现了一些类似的问题,但不是基于 R 编程,也不是基于基于列数的转置。 That is why I am writing a new question.这就是为什么我要写一个新问题。
So, I have my data as an array like in this reproducible example:所以,我将我的数据作为一个数组,就像这个可重现的例子一样:
array <- structure(c(78, 101, 22, 22, 34, 64,
68, 817, 44, 48, 42, 42, 44, 44,
69, 78, 49, 62, 76, 92, 24, 24, 27, 36,
61, 64, 44, 48, 43, 44, 42, 42, 66, 82,
43, 56), .Dim = c(2L, 9L, 2L), .Dimnames = list(c("x",
"y"), NULL, NULL))
With that, I have an array like this:有了这个,我有一个这样的数组:
, , 1
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
x 78 22 34 68 44 42 44 69 49
y 101 22 64 817 48 42 44 78 62
, , 2
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
x 76 24 27 61 44 43 42 66 43
y 92 24 36 64 48 44 42 82 56
Every column represents a different sample (9 samples).每列代表一个不同的样本(9 个样本)。 Those were repeated 100 times, here I am representing just 2 replicates.这些重复了 100 次,这里我只代表 2 个重复。 Besides, I have more rows than that (x,y,z,w...).此外,我有比这更多的行(x,y,z,w ...)。
I wanted to transpose every 9th column to a new row, so at the end I will have 9 columns with 100 rows for x followed by 100 rows for y, 100 rows for z etc. Something like this:我想将每第 9 列转换为新行,所以最后我将有 9 列,其中 x 有 100 行,y 有 100 行,z 有 100 行等。像这样:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
x 78 22 34 68 44 42 44 69 49
x 76 24 27 61 44 43 42 66 43
y 101 22 64 817 48 42 44 78 62
y 92 24 36 64 48 44 42 82 56
It can be a data.frame, matrix etc. It doesn't really matter, I just plan to export to csv format after.可以是data.frame,matrix等。没关系,我只是打算以后导出为csv格式。
You can split the array by row, bind by column, and transpose:您可以按行拆分数组、按列绑定和转置:
t(do.call(cbind, asplit(my_array, 1)))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 78 22 34 68 44 42 44 69 49
[2,] 76 24 27 61 44 43 42 66 43
[3,] 101 22 64 817 48 42 44 78 62
[4,] 92 24 36 64 48 44 42 82 56
To re-assign the row names, use:要重新分配行名称,请使用:
`row.names<-`(t(do.call(cbind, asplit(my_array, 1))), rep(row.names(my_array), each = nrow(my_array)))
Or alternatively:或者:
apply(asplit(my_array, 1:2), 2, unlist)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.