0

This might be a simple question, but I'm new to R and having trouble figuring it out. I've tried searching extensively for the answer and I cannot come up with it.

I have a dataframe that is 92:24. I would like to create an array that is (92, 2, 12) which is populated from the columns in the dataframe. I would like column 1 and 2 to be "stacked", columns 3 and 4, columns 5 and 6, and so on. The first dimension of the array should correspond to all the odd columns and the second dimension should correspond to all the even columns, with 92 rows and 12 columns in each of the 2 dimensions.

Any help would be greatly appreciated.

Thank you!

Michelle
  • 193
  • 1
  • 1
  • 6
  • Why do you want the data in this format? Maybe a `tbl_cube` could be useful, but I've never had a reason to use one of those. https://www.rdocumentation.org/packages/dplyr/versions/0.7.2/topics/tbl_cube – Andrew Brēza Aug 17 '17 at 15:34
  • 1
    Congratulations on getting started with R! I would suggest taking a look at this link so you can see how to make a great reproducible example to help others help you with your question. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – eclark Aug 17 '17 at 15:39
  • 1
    I think you can do it with `dfarray <- array(as.matrix(df), dim = c(92, 2, 12))` – Andrew Gustar Aug 17 '17 at 15:40

1 Answers1

2

Maybe this does what you want. First, create a data.frame with the appropriate dimensions.

dat <- as.data.frame(matrix(1:2208, ncol = 24))

Then, it's just a columns' shuffle and dim trick.

mat <- as.matrix(dat)
mat <- mat[, c((1:12)*2 - 1, (1:12)*2)]
dim(mat) <- c(92, 12, 2)

# See the first 5 rows
mat[1:5, , ]
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • Alternately `evens <- (1:ncol(dat) %% 2) == 0; h <- c(unlist(dat[,!evens]), unlist(dat[,evens])); array(h, dim = c(92, 12, 2))[1:5,,]` but your answer is better. – Zach Aug 17 '17 at 15:48