Reputation: 461
I have the following dataset:
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
what I want is to turn this dataset into a matrix with the amount of days (in this case 2) as the amount of columns. This is how it would like:
[,1] [,2]
[1,] 74.50 58.25
[2,] 77.50 81.25
[3,] 89.50 NA
[4,] 75.25 NA
Since this person had 4 beeps on day 1, and 2 beeps on day 2, necessarily 2 NAs must be within the matrix. I'd love to know how I could turn the above dataset in this, without manually adjusting it like I did now to make the example.
Upvotes: 0
Views: 13189
Reputation: 1
This might be simpler than others assuming that the dim of the matrix is known.
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
Upvotes: 0
Reputation: 3303
You could also use reshape
function from stats
package, but you need to transform your matrix
to data.frame
and form data.frame
to matrix
. But I think that it is more flexible way, because you create id for variable that you want to be responsible for columns (in your case day).
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
Upvotes: 1
Reputation: 132989
I agree with @flodel's comment, but here is a way:
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
Upvotes: 1