yuk
yuk

Reputation: 19870

R: parse string to a matrix

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.

Upvotes: 5

Views: 4090

Answers (4)

jburkhardt
jburkhardt

Reputation: 675

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)

Upvotes: 1

Vincent Guillemot
Vincent Guillemot

Reputation: 3429

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

df <- read.table(text=x)

To get a matrix:

m <- as.matrix(df)

Upvotes: 2

Stibu
Stibu

Reputation: 15907

Try this:

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 up into a vector with single numbers (still as character). The next line converts to numeric and the last line defines the matrix.

Upvotes: 1

joran
joran

Reputation: 173577

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.

Upvotes: 12

Related Questions