Norbert Musiał
Norbert Musiał

Reputation: 21

getting last two digits from numeric in R

I need to get last two digits from a number saved in numeric type and save it another in variable for example: a=1945 it takes last two digits and place it in b b=45

Upvotes: 0

Views: 23521

Answers (5)

Minnow
Minnow

Reputation: 1811

For posterity, this allows for tailing zeros after a decimal place. This also does not require calculating length of the string/number.

stringr has the str_sub function and f_pad_right comes from the numform package.

This gets the last digit from a number:

> library(stringr)
> library(numform)
> str_sub(f_pad_right(as.character(1.20), pad.char = 0,width = 4), - 1, - 1)
[1] "0"

Last two digits:

> str_sub(f_pad_right(as.character(1.20), pad.char = 0,width = 4), - 2, - 1)
[1] "20"

Answering the OP question:

> str_sub(f_pad_right(as.character(1945), pad.char = 0,width = 4), - 2, - 1)
[1] "45"

Upvotes: 0

Emile Tenezakis
Emile Tenezakis

Reputation: 471

you can directly use substr(), it it detects and converts numeric to string. Need to convert back to numeric. Ex :

num = c(1112, 1113)
trim = as.numeric(substr(num, nchar(num[1])-1, nchar(num[1])))

Upvotes: 2

MichaelChirico
MichaelChirico

Reputation: 34703

If you're using years, probably best (and what I use for this) is sprintf combined with %%, which will convert the number to a string, but will preserve 1905 as 05 instead of 5 (may be preferable depending on your application):

sprintf('%02d', 1999:2010 %% 100)
# [1] "99" "00" "01" "02" "03" "04" "05" "06" "07" "08" "09" "10"

Coming back to add that perhaps a more "proper" approach, in the sense of properly leveraging the date/time utilities in base R, might be to convert first to a Date and then use format:

format(.Date(365.25 * (1999:2010 - 1969.75)), '%y')
# [1] "99" "00" "01" "02" "03" "04" "05" "06" "07" "08" "09" "10"

The 1969.75 re-centers the years around 1970 (see .Date(0L)), but we need to re-re-center this to account for leap years.

Even this, however, will only be correct for about 400 years (or maybe as many as 1600?) due to leap centuries... for such a wide range of dates, the way forward with Dates is:

format(as.Date(sprintf('%d-01-01', 1999:2010)), '%y')

Upvotes: 9

Matt Tyers
Matt Tyers

Reputation: 2215

How about...

a <- 1945
b <- a - round(a, -2)
b
[1] 45

This is assuming there are no decimals, of course.

This has the side benefit of preserving sign...

a <- -1945
b <- a - round(a, -2)
b
[1] -45

Upvotes: 2

windrunn3r.1990
windrunn3r.1990

Reputation: 414

You can use the modulus operator %%

a <- 1945
b <- 1945 %% 100 
#b = 45 

Upvotes: 17

Related Questions