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.
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.
read.table
allows you to transform text into a data.frame
:
df <- read.table(text=x)
To get a matrix
:
m <- as.matrix(df)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With