Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: parse string to a matrix

Tags:

parsing

r

I have a long string (extracted from xml) that look like this (a part):

x <- "81 11780 26978 24271 6195\n92 13319 17032 233 16969\n98 17433 13883 6769 18086\n"

This is actually a Nx5 matrix of integers. How can I convert this string to a matrix mostly efficient?

substr(x,26,26) returns "\n"

I'm using R 3.1.2 in Windows x64.

like image 963
yuk Avatar asked Dec 23 '14 14:12

yuk


2 Answers

Using 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 to use byrow = TRUE, which is probably what you wanted.

like image 66
joran Avatar answered Sep 23 '22 16:09

joran


read.table allows you to transform text into a data.frame:

df <- read.table(text=x)

To get a matrix:

m <- as.matrix(df)
like image 34
Vincent Guillemot Avatar answered Sep 21 '22 16:09

Vincent Guillemot