Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a decimal number from a string in R

Tags:

r

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.

like image 797
Sailynette Garcia Avatar asked Mar 02 '15 21:03

Sailynette Garcia


People also ask

How do I split a string into characters in R?

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.

What do we use to separate whole numbers from decimals?

The decimal point is used to separate the whole number and fractional part of a number.


2 Answers

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.

like image 166
Josh O'Brien Avatar answered Oct 15 '22 00:10

Josh O'Brien


You are missing the period:

as.numeric(gsub("[^[:digit:].]", "", c("2.11abc","15.1cde",".562342rfg")))
# [1]  2.110000 15.100000  0.562342
like image 6
BrodieG Avatar answered Oct 15 '22 02:10

BrodieG