R: replace the whole part of a number but keep the decimal part unchanged

The commenters are right. It doesn’t matter how long the list of numbers is. R can do the operation in one go.

x <- c(25.01, 25.8, 25.4)
[1] 10.01 10.80 10.40

If you do run into a situation with many wide-ranging numbers and need to literally keep what comes after the decimal and pick a number to put in front, use something like this:

keep.decimal <- function(x, n=10) {
  paste0(n, gsub('\\d*(\\.\\d*)', '\\1', x))

Then you can even choose which number you want in front of it.

[1] "10.01" "10.8"  "10.4" 
keep.decimal(x, 50)
[1] "50.01" "50.8"  "50.4" 

Explanation of vectorization

When a vector is defined like x <- 1:5, R will attempt to execute operations element by element when possible. If 2 had to be added to each element of x and assigned to a new variable y, it might be difficult with a for loop:

y <- NULL
for (i in 1:length(x)) {
  y[i] <- x[i] + 2
[1] 3 4 5 6 7

But with R, this operation is simplified to:

y <- x + 2

This operational technique extends further than arithmetic. Here’s a problem to solve, write an expression that matches a lowercase letter to its capitalized counterpart. So turn this:

x <- c("a", "b", "c")
[1] "a" "b" "d"


[1] "aA" "bB" "dD"

I can write

y <- paste0(x, LETTERS[match(x, letters)])
[1] "aA" "bB" "dD"

Instead of:

y <- NULL
for(i in 1:length(x)) {
  y[i] <- paste0(x[i], LETTERS[match(x[i], letters)])
[1] "aA" "bB" "dD"

It is much faster too. As an analogy, think of restaurant service. R is your server ready to fetch what you want. If you ask your server for ketchup, they get the ketchup and deliver it. Then you ask for a napkin. They go back to get the napkin and deliver it. Then you ask for a refill.

This process takes a long time. If you would have asked for ketchup, a napkin, and a refill at the same time, the server would be able to optimize their trip to get what you want fastest. R has optimized functions built in the ‘C’ language that are lightning fast, and we exploit that speed every time we vectorize.

Browse More Popular Posts

Leave a Comment