R:改变矩阵的尺寸

时间:2014-03-16 14:46:40

标签: r matrix dimension

我有以下数据集:

day <- c(rep(17,4), rep(18,2))
beep <- c(74.50, 77.50, 89.50, 75.25, 58.25, 81.25)
m <- cbind(day, beep)
m
     day  beep
[1,]  17 74.50
[2,]  17 77.50
[3,]  17 89.50
[4,]  17 75.25
[5,]  18 58.25
[6,]  18 81.25

我想要的是将此数据集转换为具有天数(在本例中为2)作为列数的矩阵。这就是它想要的:

      [,1]  [,2]
[1,] 74.50 58.25
[2,] 77.50 81.25
[3,] 89.50    NA
[4,] 75.25    NA

由于这个人在第1天有4次哔哔声,第2天有2次哔哔声,因此必须有2个NAs必须在矩阵内。我很想知道如何在这里打开上面的数据集,而不像我现在做的那样手动调整它。

3 个答案:

答案 0 :(得分:1)

我同意@ flodel的评论,但这是一种方式:

m2 <- unstack(m, beep~day)
nrow <- max(sapply(m2, length))
m2 <- sapply(m2, function(x) {
  length(x) <- nrow
  x
})

#        17    18
#[1,] 74.50 58.25
#[2,] 77.50 81.25
#[3,] 89.50    NA
#[4,] 75.25    NA

答案 1 :(得分:1)

您还可以使用reshape包中的stats功能,但您需要将matrix转换为data.frame并将data.frame转换为matrix }。但我认为它是更灵活的方式,因为你为变量创建了你想要负责列的id(在你的情况下是一天)。

m.df<-as.data.frame(m) ## convert to data.frame
m.df$id<-ave(m.df$day,m.df$day,FUN=seq_along) ### create index with ave function (more solutions: http://stackoverflow.com/questions/8997638/numbering-by-groups )
m2<-reshape(m.df,idvar='id',timevar='day',direction='wide') ## reshape data timevar is responsible for columns and with direction you tell how data set should be expaned.
as.matrix(m2) ### convert back to matrix

答案 2 :(得分:0)

假设矩阵的暗度已知,这可能比其他方法简单。

n <- m[, "beep"]
length(n) <- 8 # Since n is a vector with 6 elements, this will make it 8 element- 
               # vector with two NAs attached.
dim(n) <- c(4, 2)  # change the dimension of the vector to a 4 by 2 matrix
print(n)

      [,1]  [,2]
[1,] 74.50 58.25
[2,] 77.50 81.25
[3,] 89.50    NA
[4,] 75.25    NA