Ying
Ying

Reputation: 11

How to remove the second digit from right (0) in the following column in R? 200517302 200517801 200519101 200519702 200521002 200521205

How to remove the second digit from right (0) in a variable in R?

17302, 17801, 19101, 19702, 21002, 21205

Upvotes: 1

Views: 36

Answers (2)

Onyambu
Onyambu

Reputation: 79338

if the second last digit is 0 then you can do:

x <- c(17302, 17801, 19101, 19702, 21002, 21205)

x %% 10 +x %/% 10 

[1] 1732 1781 1911 1972 2102 2125

Upvotes: 1

akrun
akrun

Reputation: 887781

We can use sub to match the character (.) followed the character captured as a group ((.)) at the end ($) of the string and replace with the backreference (\\1) of the captured group

as.numeric(sub(".(.)$", "\\1", v1))
#[1] 1732 1781 1911 1972 2102 2125

Or more compactly with str_remove

library(stringr)
as.numeric(str_remove(v1, ".(?=.$)"))

NOTE: If it is specific to 0, replace the . with 0 i.e.

as.numeric(str_remove(v1, "0(?=.$)"))

data

v1 <- c(17302, 17801, 19101, 19702, 21002, 21205)

Upvotes: 3

Related Questions