Using rSymPy to solve a system of equations, I got the values of x and y that solve the system in a character string like this:
"[(1.33738072607023, 27.9489435205271)]"
How should i assign those 2 values to variables x, y?
To split the string, you can use:
vect <- as.numeric(strsplit(gsub("[^[:digit:]\\. \\s]","",x)," "))
x <- vect[1]
y <- vect[2]
This deletes everything that is not a space, a point or a digit. strsplit splits the string that's left in a vector. See also the related help files.
Assignment can be done in a loop or using Gavin's function. I'd just name them.
names(vect) <-c("x","y")
vect["x"]
x
1.337381
For bigger datasets, I like to keep things together to avoid overloading the workspace with names.
Here are some steps that will do what you want to do. Can't say it is the most efficient or elegant solution available...
string <- "[(1.33738072607023, 27.9489435205271)]"
string <- gsub("[^[:digit:]\\. \\s]", "", string)
splt <- strsplit(string, " ")[[1]]
names(splt) <- c("x","y")
FOO <- function(name, strings) {
assign(name, as.numeric(strings[name]), globalenv())
invisible()
}
lapply(c("x","y"), FOO, strings = splt)
The last line would return:
> lapply(c("x","y"), FOO, strings = splt)
[[1]]
NULL
[[2]]
NULL
And we have x
and y
assigned in the global environment
> x
[1] 1.337381
> y
[1] 27.94894
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