Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help on regular expression

Tags:

regex

r

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?

like image 204
Brani Avatar asked Feb 26 '23 08:02

Brani


2 Answers

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.

like image 192
Joris Meys Avatar answered Mar 08 '23 11:03

Joris Meys


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
like image 41
Gavin Simpson Avatar answered Mar 08 '23 11:03

Gavin Simpson