Search code examples
arraysrdimensionspopulate

Fill an array by specific columns in R


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!


Solution

  • 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, , ]