Reputation: 183
I'm completely new to R and I'm making a program that will solve a system of equations from a string like for example this:
my_string <- "3x+2y=0; -1x+4y=-1; 13x-2y=11"
and only one thing prevents me from finishing it.
After some replace instructions I could obtain this string:
my_string <- "3, 2, 0, -1, 4, -1, 13, -2, 11"
I want to build a 3*3
table but can't manage to turn this string into a form which would enable me to do so (a vector). I've tried with data.frame
, as.numeric
, lapply
, noquote
and other functions but couldn't find an answer.
The result should be :
x <- matrix(c(my_string), ncol=3,nrow=3,byrow=TRUE)
x
# [,1] [,2] [,3]
# [1,] 3 2 0
# [2,]-1 4 -1
# [3,]13 -2 11
Thank you in advance.
Upvotes: 0
Views: 124
Reputation: 10437
You can use scan
to parse delimited values in a file or character vector.
matrix(scan(text = my_string, sep = ",", what = 1L), ncol = 3, byrow = TRUE)
#Read 9 items
# [,1] [,2] [,3]
#[1,] 3 2 0
#[2,] -1 4 -1
#[3,] 13 -2 11
Upvotes: 1
Reputation: 206197
You should user strsplit
to split based on commas and then turn those into numeric values
vals <- as.numeric(strsplit(my_string, ",")[[1]])
x <- matrix(vals, ncol=3,nrow=3,byrow=TRUE)
x
# [,1] [,2] [,3]
# [1,] 3 2 0
# [2,] -1 4 -1
# [3,] 13 -2 11
Upvotes: 0