Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate string: s = "start=70 end=200 step=5"

Tags:

string

r

I have a string from an external file:

"start=70 end=200 step=5"

In general: it could be any similar string with arbitrary number of parameters. To avoid @Martin Mächler 's ire, see also Evaluate expression given as a string: The input format is given, I cannot change it.

Here is my solution to make this a named vector, using the no-no-no-eval:

s = "start=70 end=200 step=5"
lazyeval::lazy_eval(paste0("c(", stringr::str_replace_all(s, " ", ","),")"))
# start   end  step 
#   70   200     5 

Any more safe, elegant or Martin-pleasing alternative?

like image 457
Dieter Menne Avatar asked Sep 09 '26 10:09

Dieter Menne


2 Answers

Regular expressions to the rescue (with risks):

s <-"start=70 end=200 step=5"
re <- gregexpr("\\S+=\\d+", s)
regmatches(s, re)
# [[1]]
# [1] "start=70" "end=200"  "step=5"  

spl <- strsplit(regmatches(s, re)[[1]], "=")
setNames(as.numeric(sapply(spl, `[[`, 2)), sapply(spl, `[[`, 1))
# start   end  step 
#    70   200     5 
like image 60
r2evans Avatar answered Sep 11 '26 00:09

r2evans


Quite cumbersome and unintelligent, but without eval and it kinda demonstrates how it might be possibly done.

require(tidyr)

s <- "start=70 end=200 step=5"
s2 <- unlist(strsplit(s, " "))
s2 <- data.frame(s2) %>% separate(s2, c("name","value"), sep="=")
s <- s2$value
names(s) <- s2$name

result:

start   end  step 
 "70" "200"   "5"
like image 23
jyr Avatar answered Sep 11 '26 00:09

jyr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!