Home > Software design >  Matrix Creation Automation
Matrix Creation Automation

Time:10-03

I have roughly 1000 matrices which are formatted like this:

01202
10000
22110
22210
22222

I need them to look like this:

matrix1 <- rbind(c(0,1,2,0,2),c(1,0,0,0,0),c(2,2,1,1,0),c(2,2,2,1,0),c(2,2,2,2,2))

Any suggestions for how I could get this done? Doing this all by hand would take forever.. Thanks!

CodePudding user response:

If the numbers are characters a one-liner can do it.

x <- scan(text='01202
10000
22110
22210
22222
', what = character())
x
#> [1] "01202" "10000" "22110" "22210" "22222"

t(sapply(strsplit(x, ""), as.numeric))
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]    0    1    2    0    2
#> [2,]    1    0    0    0    0
#> [3,]    2    2    1    1    0
#> [4,]    2    2    2    1    0
#> [5,]    2    2    2    2    2

Created on 2022-10-02 with reprex v2.0.2

CodePudding user response:

You could directly use:

read.table(text = gsub("", " ", x))
  V1 V2 V3 V4 V5
1  0  1  2  0  2
2  1  0  0  0  0
3  2  2  1  1  0
4  2  2  2  1  0
5  2  2  2  2  2  

or if you want it in matrix form:

as.matrix(read.table(text = gsub("", " ", x)))
     V1 V2 V3 V4 V5
[1,]  0  1  2  0  2
[2,]  1  0  0  0  0
[3,]  2  2  1  1  0
[4,]  2  2  2  1  0
[5,]  2  2  2  2  2

x is one of the matrices you have

  • Related