1

I am very new to R. I have a numeric vector, let's say data <- c(1,3, 5, 10, 101). What I need is to have every element as a character, add a zero to single digits, and not have more than two characters in every element. I am using the following code:

pad <- str_pad(data, width = 2, side = "left", pad="0")  

But this still does not reduce "101" to "10". Any suggestions?

This is different from an earlier thread on padding which does not provide me an answer to how to reduce "101" to "10"

  • 1
    `str_pad` is not a base R function. Please include the names of the relevant packages that you are using. – lmo Feb 06 '17 at 20:02
  • 1
    Possible duplicate of [Adding leading zeros using R](http://stackoverflow.com/questions/5812493/adding-leading-zeros-using-r) – lmo Feb 06 '17 at 20:03
  • 1
    I referred to "Adding leading zeros using R ". But I couldn't find the answer to reducing 3 digit characters to two digits. The code I have written is from that thread itself. – shashank rai Feb 06 '17 at 20:06
  • Not sure why you'd want to do this, but wrap the result in `substr`: `substr(str_pad(data, width = 2, side = "left", pad="0"), 1, 2)`. – lmo Feb 06 '17 at 20:11

2 Answers2

2
library(stringr)

data <- c(1,3, 5, 10, 101)
data <- as.character(data)
data <- strtrim(data, 2)
data <- str_pad(data, width = 2, side = "left", pad = "0")
data
# [1] "01" "03" "05" "10" "10"

I split up the steps but you could easily nest some of those steps as well.

MeetMrMet
  • 1,349
  • 8
  • 14
0

Here's a function that would do what you want

str_pad = function(data){    
     data = ifelse(abs(data)<10,
                         paste("0", data,sep = ""),
                         ifelse(abs(data)>100,
                                substr(as.character(data),1,2),
                                as.character(data))) 
    return(data)
}
d.b
  • 32,245
  • 6
  • 36
  • 77