评估字符串:s =“ start = 70 end = 200 step = 5”

时间:2019-02-15 18:26:15

标签: r string

我有一个来自外部文件的字符串:

"start=70 end=200 step=5"

通常:它可以是具有任意数量参数的任何相似字符串。为避免@MartinMächler的烦恼,另请参见Evaluate expression given as a string:给出了输入格式,我无法更改。

这是我使用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 

还有其他更安全,更优雅或更讨人喜欢的选择吗?

3 个答案:

答案 0 :(得分:4)

正则表达式to the rescue(带有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 

答案 1 :(得分:2)

非常笨拙且不智能,但是没有评估,它有点说明了如何实现。

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

结果:

start   end  step 
 "70" "200"   "5"

答案 2 :(得分:2)

另一种使用scan()和base-R函数的方法

s = "start=70 end=200 step=5"
sapply(scan(text=s,sep=" ",what=character(),quiet=T),
   function(x) { 
       x<-scan(text=x,sep="=",what=character(),quiet=T)
       setNames(as.numeric(x[2]),x[1]) },USE.NAMES = F)