Home > database >  Conditional paste0 in R
Conditional paste0 in R

Time:07-02

My dataframe looks like this:

N = 1000

a <- rnorm(N)
b <- rnorm(N)

df <- data.frame(a, b)

I would like to set up a conditional paste0 if the value of a is smaller than 10.

Specifically, I would like to print the value '0' (with no spaces) in front of the number in a if a < 10.

How can I do this? Thank you

CodePudding user response:

You could do: ifelse(a < 0, paste0("0", a), a)

You might want to use abs(a) < 10 or take special care of negative numbers in other ways.

CodePudding user response:

I used @harre solution and implemented it in a more general function that take negative too.

For future questions please provide a smaller dataset, your's don't need 1000 lines dataframe.

a <- seq(-14, 14, by = 4)

text_number <- function(x){
  
  neg <- x < 0
  x <- abs(x)

  res <- ifelse(x < 10, paste0("0", x), x)
  res <- ifelse(neg, paste0("-", res), res)

  return(res)
}

text_number(a)
  • Related