Search code examples
arraysrcoercion

How to easily coerce all values in a multidimensional array to numeric


So I have an n X m X z array. And all of it's values are potentially numeric, but currently characters (e.g. '4.02'). Is there an easy way to coerce all of the values to numeric, without going through a big loop? e.g. I can just write:

for(i in 1:n){
  for(j in 1:m){
    A[i, j, ] = as.numeric(A[i, j, ])
  }
}

But this is slow and ugly. Is there a better way?


Solution

  • Well, an array in R can only hold one data type, so they are either all numeric or all character. Another easy way to change from character to numeric is just to use class()<-. For example

    A <- array(c("4","5","6.2","7","8.8","9","10","11.5", 
        "12","12.2","13", "14.1"), dim=list(2,2,3))
    str(A)
    # chr [1:2, 1:2, 1:3] "4" "5" "6.2" "7" "8.8" "9" "10" ...
    
    class(A) <- "numeric"
    str(A)
    # num [1:2, 1:2, 1:3] 4 5 6.2 7 8.8 9 10 11.5 12 12.2 ...
    A