'Convert Character String to Matrix
I have a large (rectangular) vector of strings, e.g:
my.strings <- c("1234567", "1234567", "1234567", "1234567")
which I would like to convert to a matrix:
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] 1 2 3 4 5 6 7
# [2,] 1 2 3 4 5 6 7
# [3,] 1 2 3 4 5 6 7
# [4,] 1 2 3 4 5 6 7
Is there a simple way to do this in R? (Unfortunately, yes the strings of numbers are indeed character strings and not numeric.)
Solution 1:[1]
Another possible solution:
library(tidyverse)
my.strings <- c("1234567", "1234567", "1234567", "1234567")
my.strings %>%
sapply(function(x) str_split(x,"") %>% unlist %>% as.numeric) %>%
unname %>% t
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#> [1,] 1 2 3 4 5 6 7
#> [2,] 1 2 3 4 5 6 7
#> [3,] 1 2 3 4 5 6 7
#> [4,] 1 2 3 4 5 6 7
Solution 2:[2]
Here's another way:
matrix(as.numeric(unlist(strsplit(my.strings, ""))), nrow = length(my.strings), byrow=T)
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 2 3 4 5 6 7
[2,] 1 2 3 4 5 6 7
[3,] 1 2 3 4 5 6 7
[4,] 1 2 3 4 5 6 7
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | PaulS |
| Solution 2 |
