Tanushree Chandhok
Tanushree Chandhok

Reputation: 57

Finding the position of decimal point in an integer or a string

If i want to determine the position of a decimal point in an integer, for example, in 524.79, the position of the decimal point is 4, and that is what I want as output in R; which function or command should i use? I have tried using gregexpr as well as regexpr but each time the output comes out to be 1.

This is what I did :

x <- 524.79

gregexpr(pattern = ".", "x")

The output looks like this:

[[1]]

[1] 1

attr(,"match.length")

[1] 1

attr(,"useBytes")

[1] TRUE

Upvotes: 0

Views: 451

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522244

We could actually use a regex here:

x <- "524.79"
nchar(sub("(?<=\\.)\\d+", "", x, perl=TRUE))

4

Upvotes: 3

akrun
akrun

Reputation: 887621

The . is a metacharacter which means any character. It either needs to be escaped (\\.) or place it inside square brackets [.] or use fixed = TRUE to get the literal character

as.integer(gregexpr(pattern = ".", x, fixed = TRUE))
#[1] 4

Or a compact option is str_locate

library(stringr)
unname(str_locate(x, "[.]")[,1])
#[1] 4

The second issue in the OP's solution is quoting the object x. So, the gregexpr locates the . as 1 because there is only one character "x" and it is the first position

data

x <- 524.79

Upvotes: 3

Related Questions