Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract digit from numeric in r

Tags:

r

decimal

extract

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.

like image 201
coding_heart Avatar asked Feb 19 '14 00:02

coding_heart


People also ask

How do I extract a character from a number in R?

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 ...

How do I extract the last digit in R?

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.


1 Answers

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)
like image 133
alexwhan Avatar answered Oct 15 '22 04:10

alexwhan