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


Usage scan

:

matrix(scan(text = x),nrow = 3,byrow = TRUE)
Read 15 items
     [,1]  [,2]  [,3]  [,4]  [,5]
[1,]   81 11780 26978 24271  6195
[2,]   92 13319 17032   233 16969
[3,]   98 17433 13883  6769 18086

      



Edited for use byrow = TRUE

, which is probably what you need.

+9


source


read.table

allows converting text to data.frame

:

df <- read.table(text=x)

      



To get matrix

:

m <- as.matrix(df)

      

+2


source


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


x <- "81 11780 26978 24271 6195\n92 13319 17032 233 16969\n98 17433 13883 6769 18086\n"
#generate data frame
data <- read.csv(textConnection(x),sep=" ",header=F)
#generate matrix
data <- as.matrix(data)

      

+1


source







All Articles