For example:
c("2.11abc","15.1cde",".562342rfg")
How to split the numeric out of this vector? The vector I would like to have is
c(2.11, 15.1, 0.562342)
I tried
gsub("[^[:digit:]]", "", a)
but the result was
c(211, 151 ,562342)
I really appreciate your help.
To split string in R, use the strsplit() method. The strsplit() method accepts the character or vector string and the character string to split and return the formatted string.
The decimal point is used to separate the whole number and fractional part of a number.
If have more troublesome strings, in which periods can appear outside of the number part of the string, you might want to use something like this.
library(gsubfn)
## A possibly more realistic character vector
x <- c("2.11abc.def","a.b-15.1cde",".562342rfg", "abcdef")
getNumberPart <- function(x) {
pat <- "(-?(\\d*\\.*\\d+|\\d+\\.))"
strapply(x, pattern=pat, FUN=as.numeric, simplify=TRUE, empty=NA)
}
getNumberPart(x)
# [1] 2.110000 -15.100000 0.562342 NA
Do note that if a string contains more than one number, strapply()
will extract all of them, and will return the overall result as a list (rather than a simple vector) with one list element per input string.
You are missing the period:
as.numeric(gsub("[^[:digit:].]", "", c("2.11abc","15.1cde",".562342rfg")))
# [1] 2.110000 15.100000 0.562342
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