I would like to extract the first digit after a decimal place from a numeric vector in R. Is there a way to do this without turning it into a character string? For example:
x <- c(1.0,1.1,1.2)
I would like the function to return a vector:
0,1,2
thanks.
In this method to extract numbers from character string vector, the user has to call the gsub() function which is one of the inbuilt function of R language, and pass the pattern for the first occurrence of the number in the given strings and the vector of the string as the parameter of this function and in return, this ...
To get the last n characters from a string, we can use the stri_sub() function from a stringi package in R. The stri_sub() function takes 3 arguments, the first one is a string, second is start position, third is end position.
There'll be a bunch of ways, but here's one:
(x %% 1)*10
# [1] 0 1 2
This assumes there's only ever one digit after the decimal place. If that's not the case:
floor((x %% 1)*10)
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