Brani
Brani

Reputation: 6784

Help on regular expression

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?

Upvotes: 4

Views: 199

Answers (3)

G. Grothendieck
G. Grothendieck

Reputation: 269461

strapply in the gsubfn package makes it fairly easy to extract numbers from strings using only a relatively simple regexp. Here s is the input string and v is a numeric vector with the two numbers:

library(gsubfn)
v <- strapply(s, "[0-9.]+", as.numeric)[[1]]
x <- v[1]
y <- v[2]

Upvotes: 2

Gavin Simpson
Gavin Simpson

Reputation: 174788

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

Upvotes: 2

Joris Meys
Joris Meys

Reputation: 108523

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.

Upvotes: 4

Related Questions