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.)
CodePudding user response:
We could use strsplit to split at '', and then rbind the list elements after converting the type
do.call(rbind, type.convert(strsplit(my.strings, ""), as.is = TRUE))
[,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
Here, we assume the strings have the same number of characters (nchar). If it is different, the lengths will be different and thus have to pad NA before reshaping to matrix
lst1 <- type.convert(strsplit(my.strings, ""), as.is = TRUE)
mx <- max(lengths(lst1))
do.call(rbind, lapply(lst1, `length<-`, mx))
CodePudding user response:
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
CodePudding user response:
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
