0

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.

Jolanda Kossakowski
  • 451
  • 2
  • 6
  • 14
  • It seems like a bad idea (IMHO) to turn your data into that format. Can I ask why you want to do that? Is it so you can later process the data column-by-column or row-by-row? There are certainly better approaches if you tell us a little more about your final goal. – flodel Mar 16 '14 at 14:53
  • @flodel: I want to make a matrix per participant with the amount of days as columns and fill it with the beeps. After that I mean to attach these matrices into an array with abind(). That is why I want to change my dimensions. I need an array in order to load my data into JAGS for my research. – Jolanda Kossakowski Mar 16 '14 at 15:01

3 Answers3

1

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
Roland
  • 127,288
  • 10
  • 191
  • 288
1

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
Maciej
  • 3,255
  • 1
  • 28
  • 43
0

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