R:用块重塑数据 - 更优雅的方式

时间:2015-11-19 15:44:40

标签: r reshape reshape2

我偶然发现了以下事情。我阅读了重塑手册,但仍然丢失了。 是否有一种有效且更优雅的方式来重塑偶数块的矩阵? 生成矩阵和重新整形矩阵的代码如下。

# current matrix
x <- matrix(sample(20*9), 20, 9)
colnames(x) <- c(paste("time",c(1:3),sep="_"),
paste("SGNL", 1, c(1:3), sep="_"),
paste("SGNL", 2, c(1:3), sep="_"))
# reshaped matrix
x.reshaped <- rbind( x[,c(1,4,7)], x[,c(2,5,8)], x[,c(3,6,9)] )
colnames(x.reshaped) <- sub("\\_1$", "", colnames(x.reshaped))

谢谢!

3 个答案:

答案 0 :(得分:2)

如果您想使用基于名称而非基于位置的方法,那么您应该从“data.table”查看melt

library(data.table)
melt(as.data.table(x), measure.vars = patterns("time", "SGNL_1", "SGNL_2"))

示例输出:

head(melt(as.data.table(x), measure.vars = patterns("time", "SGNL_1", "SGNL_2")))
#    variable value1 value2 value3
# 1:        1     48    110    155
# 2:        1     67     35    140
# 3:        1    102     55     72
# 4:        1    161     39     66
# 5:        1     36    137     99
# 6:        1    158    169     85

或者,在基地R:

patts <- c("time", "SGNL_1", "SGNL_2")
sapply(patts, function(y) c(x[, grep(y, colnames(x))]))
#       time SGNL_1 SGNL_2
#  [1,]   48    110    155
#  [2,]   67     35    140
#  [3,]  102     55     72
#  [4,]  161     39     66
#  [5,]   36    137     99
# .
# .
# .
# .
# [56,]   13      1     84
# [57,]   40     46     95
# [58,]  152      7    178
# [59,]   81     79    123
# [60,]   50    101    146

使用set.seed(1)生成的数据。

答案 1 :(得分:1)

我们可以在seq中创建矩阵子集(基于list生成的索引),然后rbind一起创建矩阵。

do.call(rbind, lapply(1:3, function(i) x[,seq(i, length.out=3, by=3)]))

或使用for循环

 m2 <- c()
 for(i in 1:3) { m2 <- rbind(m2, x[,seq(i, length.out=3, by=3)])}

答案 2 :(得分:0)

x[,c(matrix(1:9, 3, byrow=TRUE))] # or shorter:
x[,matrix(1:9, 3, byrow=TRUE)]
相关问题