[R] Regex exercise
Marc Schwartz
marc_schwartz at me.com
Fri Aug 20 23:42:04 CEST 2010
On Aug 20, 2010, at 4:16 PM, RICHARD M. HEIBERGER wrote:
> Bert,
>
> we can save a lot of time by using paste and then only one call to eval and
> parse.
>
>> x2 <- c("1", "2:5", "3:6", "4", "8", "5:7", "10")
>> system.time(for (i in 1:100) unlist(lapply(parse(text=x2),eval)))
> user system elapsed
> 0.06 0.00 0.03
>> system.time(for (i in 1:100) eval(parse(text=paste("c(",paste(x2,
> collapse=","),")"))))
> user system elapsed
> 0.01 0.00 0.03
>>
>
> Rich
Building on Rich's approach:
> x
[1] "1 2 -5, 3- 6 4 8 5-7 10"
> eval(parse(text = paste("c(", paste(strsplit(gsub(" *- *", ":", x), split = " +|, +")[[1]], collapse = ","), ")")))
[1] 1 2 3 4 5 3 4 5 6 4 8 5 6 7 10
The key inner part is:
> strsplit(gsub(" *- *", ":", x), split = " +|, +")[[1]]
[1] "1" "2:5" "3:6" "4" "8" "5:7" "10"
HTH,
Marc Schwartz
More information about the R-help
mailing list