Search code examples
rclassmatrixnumeric

Efficient way to change the class of several matrices in R


I have several matrices and I would like to apply something like

class(matrix) <- "numeric" to all of them at once, i.e. the class of all matrices should be changed to numeric.

Do you know how to do this?

dput(matrix[1:3,]) results in structure(c(285.789361223578, 282.564165145159, 273.633228540421, 256.789452806115, 260.808130130172, 241.718192100525, 266.765343174338, 267.881099879742, 250.710165724158, 284.365977942944, 281.670583188534, 268.735618144274, 264.118778035045, 262.856532484293, 254.31867428124, 286.250801086426, 284.585711210966, 268.984649181366, 286.17267370224, 284.429456442595, 267.478255555034, 275.10055847466, 274.141056537628, 259.477523118258, 246.454664766788, 252.470473349094, 232.699362188578, 284.998321458697, 283.73363442719, 269.555955678225, 0, 0, 0), dim = c(3L, 11L), dimnames = list(NULL, c("", "", "", "", "", "", "", "", "", "", "vec")))


Solution

  • In this examples all matrix variables of the current environment are converted to numeric. See the warning in the case where matrix cannot be converted to numeric.

    var1 <- matrix(1:10, 5, 2)
    var2 <- matrix(as.character(5:13), 3,3)
    var3 <- letters[1:5]
    var4 <- matrix(letters[1])
    
    print(sapply(mget(ls()), typeof))
    #>        var1        var2        var3        var4 
    #>   "integer" "character" "character" "character"
    
    for (i in ls()[sapply(mget(ls()), is.matrix)])
      assign(i, as.numeric(get(i)))
    #> Warning in assign(i, as.numeric(get(i))): NAs introduced by coercion
    
    print(sapply(mget(ls()), typeof))
    #>           i        var1        var2        var3        var4 
    #> "character"    "double"    "double" "character"    "double"
    

    Created on 2023-06-03 with reprex v2.0.2