Add leading numbers based on range of numbers

Viewed 69

I have years which are represented by either four or two digits in the same variable. For example c(2010, 1980, 60, 69, 75, 5, 15)

Every 2 digits between 60 and 75 should get a 19 in front of itself.

Every 2 digits between 10 and 20 should get a 20 in front of itself.

sprintf seems the way to go but how exactly? Thanks in advance!

5 Answers

What about this?

pos <- nchar(x) < 4
x[pos] <- x[pos] + 2000
x[x > 2020] <- x[x > 2020] - 100
x
# [1] 2010 1980 1960 1969 1975 2005 2015

Data

x <- c(2010, 1980, 60, 69, 75, 5, 15)
x <- c(2010, 1980, 60, 69, 75, 5, 15)
p <- ifelse(x>=10 & x<=20, "20", ifelse(x>=60 & x<=75, "19", ""))
paste0(p, x)

[1] "2010" "1980" "1960" "1969" "1975" "5"    "2015"

OP said:

Every 2 digits between 10 and 20 should get a 20 in front of itself.

5 is not a 2 digit number between 10 and 20!

Using vectorization and booleans:

x + (x>=60 & x<=75)*1900 + (x>=10 & x<=20)*2000
[1] 2010 1980 1960 1969 1975    5 2015

Base R solution:

ifelse(nchar(x) < 4 & x > 20, x + 1900, ifelse(nchar(x) < 4 & x >= 10, x + 2000, x))

Data:

x <- c(2010, 1980, 60, 69, 75, 5, 15)

Use step-wise logic:

x <- c(2010, 1980, 60, 69, 75, 5, 15)
x[x <= 20] <- x[x <= 20] + 2000 # less than 20 -> add 2000
x[x <= 75] <- x[x <= 75] + 1900 # remaining & less than 75 -> add 1900
x
#2010 1980 1960 1969 1975 2005 2015
Related