NoobR
NoobR

Reputation: 321

How to I add a leading numeric identifier (not necessarily zero) to a character string in r

I apologize if this is a duplicate, I've searched through all of the "add leading zero" content I can find, and I'm struggling to find a solution I can work with. I have the following:

siteid<-c("1","11","111")
modifier<-c("44","22","11")
df<-data.frame(siteid,modifier)

and I want a modified siteid that is always six (6) characters long with zeroes to fill the gaps. The Site ID can vary in nchar from 1-3, the modifier is always a length of 2, and the number of zeroes can vary depending on the length of the site ID (so that 6 is always the final modified length).

I would like the following final output:

df
#  siteid modifier mod.siteid
#1      1       44     440001
#2     11       22     220011
#3    111       11     110111

Thanks for any suggestions or direction. This could also be numeric, but it seems like character manipulation has more options...?

Upvotes: 0

Views: 49

Answers (2)

Wimpel
Wimpel

Reputation: 27802

siteid<-c("1","11","111")
modifier<-c("44","22","11")
df<-data.frame(siteid,modifier, stringsAsFactors = FALSE)

df$mod.siteid = paste0( df$modifier, 
                        formatC( as.numeric(df$siteid), width = 4, format = "d", flag="0") )

df

#   siteid modifier mod.siteid
# 1      1       44     440001
# 2     11       22     220011
# 3    111       11     110111

Upvotes: 2

s_baldur
s_baldur

Reputation: 33603

The vocabulary here is left pad and paste here is one way using sprintf()::

df$mod.siteid <- with(df, sprintf("%s%04d", modifier, as.integer(siteid)))

# Note: 
# code simplified thanks to suggestion by Maurits.

Output:

      siteid modifier mod.siteid
1      1       44     440001
2     11       22     220011
3    111       11     110111

Data:

df <- data.frame(
  siteid   = c("1", "11", "111"),
  modifier = c("44", "22", "11"),
  stringsAsFactors = FALSE
)  

Extra: If you don't want to left pad with 0, then using the stringi package is one option: with(df, paste0(modifier, stringi::stri_pad_left(siteid, 4, "q")))

Upvotes: 2

Related Questions