0

I am trying to add "S00", "S0", or "S" to strings in tst if they are 1 or 2 or 3 times long, respectively. So the outcome would be S004,S008,S009,S022,S051,...,S753.

been trying with ifelse and grepl but it was not successful:

tst <- as.character(c(4,8,9,22,51,56,57,12,15,150,147,852,654,753))
ifelse(grepl("[0-9]{1} ", tst), paste("S00", tst,sep = ""), 
    ifelse(grepl("[0-9]{2} ", tst), paste("S0", tst,sep = ""), "S"))
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Seymoo
  • 177
  • 2
  • 15
  • 4
    Easy: `sprintf("S%03d", as.numeric(tst))`. BTW, why `as.character`? If you really, really need `paste` it will coerce to character on its own. – Rui Barradas Dec 13 '18 at 12:31
  • @RuiBarradas, that was smart, Thanks! Anyways, do you know how can I use grepl to for captuirng those pattern in tst? because I quite often need to do find these this pattern and add different letters to them, based on their length. – Seymoo Dec 13 '18 at 13:01
  • 1
    if you want to count the number of digits see [count number of digits in a string in r](https://stackoverflow.com/questions/52447553/count-number-of-digits-in-a-string-in-r). If you want to count the number of *consecutive* digits you will need another way. – Rui Barradas Dec 13 '18 at 15:01

0 Answers0