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?
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
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"
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