Reputation: 10626
I have line like this:
x<-c("System configuration: lcpu=96 mem=196608MB ent=16.00")
I need to the the value equal to ent and store it in val object in R
I am doing this not not seem to be working. Any ideas?
val<-x[grep("[0-9]$", x)]
Upvotes: 1
Views: 90
Reputation: 4767
Using rex may make this type of task a little simpler.
Note this solution correctly includes .
in the capture, as does G. Grothendieck's answer.
x <- c("System configuration: lcpu=96 mem=196608MB ent=16.00")
library(rex)
val <- as.numeric(
re_matches(x,
rex("ent=",
capture(name = "ent", some_of(digit, "."))
)
)$ent
)
#>[1] 16
Upvotes: 0
Reputation: 269481
If ent is always at the end then:
sub(".*ent=", "", x)
If not try strapplyc
in the gsubfn package which returns only the portion of the regular expression within parentheses:
library(gsubfn)
strapplyc(x, "ent=([.0-9]+)", simplify = TRUE)
Also it could be converted to numeric at the same time using strapply
:
strapply(x, "ent=([.0-9]+)", as.numeric, simplify = TRUE)
Upvotes: 3