R: split string into matrix
I have a long string (extracted from xml) that looks like this (part):
x <- "81 11780 26978 24271 6195\n92 13319 17032 233 16969\n98 17433 13883 6769 18086\n"
It is actually an Nx5 matrix of integers. How do I convert this string to a matrix that is mostly efficient?
substr(x,26,26)
returns "\n"
I am using R 3.1.2 on Windows x64.
+3
source to share
4 answers
Try the following:
x.split <- gsub(x,"\n","")
x.num <- as.numeric(x.split)
x.matrix <- matrix(x.num,ncol=5,byrow=TRUE)
The first line splits the long character into a vector of single numbers (still as a character). The next line is converted to numeric, and the last line defines the matrix.
+1
source to share