How to Set Character Matrix to Numeric in R (Example Code)
In this tutorial you’ll learn how to set a all columns of a character matrix to numeric in the R programming language.
Creation of Example Data
my_matrix <- matrix(as.character(11:25), # Character matrix in R nrow = 5) my_matrix # Show character matrix in RStudio # [,1] [,2] [,3] # [1,] "11" "16" "21" # [2,] "12" "17" "22" # [3,] "13" "18" "23" # [4,] "14" "19" "24" # [5,] "15" "20" "25" |
my_matrix <- matrix(as.character(11:25), # Character matrix in R nrow = 5) my_matrix # Show character matrix in RStudio # [,1] [,2] [,3] # [1,] "11" "16" "21" # [2,] "12" "17" "22" # [3,] "13" "18" "23" # [4,] "14" "19" "24" # [5,] "15" "20" "25"
Example: Set Character Matrix to Numeric
my_matrix_new <- matrix(as.numeric(my_matrix), # Change character to numeric matrix ncol = ncol(my_matrix)) my_matrix_new # Show numeric matrix in RStudio # [,1] [,2] [,3] # [1,] 11 16 21 # [2,] 12 17 22 # [3,] 13 18 23 # [4,] 14 19 24 # [5,] 15 20 25 |
my_matrix_new <- matrix(as.numeric(my_matrix), # Change character to numeric matrix ncol = ncol(my_matrix)) my_matrix_new # Show numeric matrix in RStudio # [,1] [,2] [,3] # [1,] 11 16 21 # [2,] 12 17 22 # [3,] 13 18 23 # [4,] 14 19 24 # [5,] 15 20 25
Further Resources & Related Articles
You may have a look at the following list of R programming tutorials. They discuss topics such as data conversion, character strings, extracting data, and matrices.