Search code examples
rlistmultidimensional-arraycoercion

Filling a 3D array in R: How to avoid coercion to list?


I have preallocated a 3D array and try to fill it with data. However, whenever I do this with a previously defined data.frame collumn, the array gets mysteriously converted to a list, which messes up everything. Converting the data.frame collumn to a vector does not help it.

Example:

exampleArray <- array(dim=c(3,4,6))
exampleArray[2,3,] <- c(1:6) # direct filling works perfectly

exampleArray
str(exampleArray) # output as expected

Problem:

exampleArray <- array(dim=c(3,4,6))
exampleContent <- as.vector(as.data.frame(c(1:6)))
exampleArray[2,3,] <- exampleContent # filling array from a data.frame column
# no errors or warnings

exampleArray    
str(exampleArray)  # list-like output!

Is there any way I can get around this and fill up my array normally?

Thanks for your suggestions!


Solution

  • Try this:

    exampleArray <- array(dim=c(3,4,6))
    exampleContent <- as.data.frame(c(1:6))
    > exampleContent[,1]
    [1] 1 2 3 4 5 6
    exampleArray[2,3,] <- exampleContent[,1] # take the desired column
    # no errors or warnings
    str(exampleArray)
    int [1:3, 1:4, 1:6] NA NA NA NA NA NA NA 1 NA NA ...
    

    You were trying to insert data frame in array, which won't work. You should use the dataframe$column or dataframe[,1] instead.

    Also, as.vector doesn't do anything in as.vector(as.data.frame(c(1:6))), you were probably after as.vector(as.data.frame(c(1:6))), although that doesn't work:

    as.vector(as.data.frame(c(1:6)))
    Error: (list) object cannot be coerced to type 'double'