alirazi
alirazi

Reputation: 161

Convert string to 2 column matrix - R

I have a string in this format X1 Y1; X2 Y2; … Xn Yn representing numbers . How can I convert it to a matrix in this format?

int [1:n, 1:2]
X1 Y1
X2 Y2
....
Xn Yn

Code:

string <- "11 12;20 21;34 35; 44 55; 66 77; 88 99"
mtx <- as.integer(do.call(rbind, strsplit(strsplit(string, "\\s*;\\s*")[[1]], "\\s+")))

Upvotes: 0

Views: 145

Answers (1)

r2evans
r2evans

Reputation: 160447

vec <- c("X1 Y1", "X2 Y2", "Xn Yn")
do.call(rbind, strsplit(vec, "\\s+"))
#      [,1] [,2]
# [1,] "X1" "Y1"
# [2,] "X2" "Y2"
# [3,] "Xn" "Yn"

For the whole string,

string <- "X1 Y1;X2 Y2;Xn Yn"
do.call(rbind, strsplit(strsplit(string, "\\s*;\\s*")[[1]], "\\s+"))
#      [,1] [,2]
# [1,] "X1" "Y1"
# [2,] "X2" "Y2"
# [3,] "Xn" "Yn"
  • I use "\\s*;\\s*" (literal semi-colon with surrounding blank space) in case there are or may be spaces around the semi-colons that we are not interested in preserving;
  • I use "\\s+" (one or more blank-space) in case it could be "X1 Y1" (two spaces).

With your updated string and a slight update to code in my comment:

string <- "11 12;20 21;34 35; 44 55; 66 77; 88 99"
mtx <- do.call(rbind, strsplit(strsplit(string, "\\s*;\\s*")[[1]], "\\s+"))
mtx <- array(as.integer(mtx), dim=dim(mtx))
mtx
#      [,1] [,2]
# [1,]   11   12
# [2,]   20   21
# [3,]   34   35
# [4,]   44   55
# [5,]   66   77
# [6,]   88   99

Upvotes: 2

Related Questions