-1

I am trying to pad a string tidyverse.For example, i want to:

  1. detect certain format word, like "1" by using str_detect;
  2. paste such character on both side with different string: left side is "0", right side is ".00";

I learned that str_pad has "side=both",but how can I achieve my purpose? Thanks~~!

here is my code:

jimma3 <- jimma2 %>% 
    mutate(
      Enterdateofexam2 = if_else(str_detect(Enterdateofexam2, "\\d"), 
      str_pad(as.character(Enterdateofexam2), 5, side = "both", pad = ".")
) 

The problem is that I can only define one format (".") with width 1 in pad=" ", but what if i want to paste different string on both side and turn it into like :"01.00"? thanks a lot~!

  • 5
    "string padding" is usually filling out a string of uncertain length to a known length with a certain character, so, e.g., `1` becomes `001`, `12` becomes `012`, `123` stays as `123`. The main convenience of `str_pad` is you don't have to worry about the lengths of the input strings to get the right output length. What you're doing doesn't seem like string padding - you want to add a fixed number of characters on both sides of the string, but they're not all the same character. Just use `paste0` directly, `paste0("0", Enterdateofexam2, ".00")`, – Gregor Thomas Aug 16 '21 at 16:02
  • 1
    If that doesn't work or you need more help, please make your example reproducible by sharing a bit of data in a copy/pasteable format and providing more examples of input than `"1"`. – Gregor Thomas Aug 16 '21 at 16:04
  • Thanks for your answer, the paste0 works, but it applies all variables, in other words, it ignores the if ... all obs. are pasted by 0 and ".00". –  Aug 16 '21 at 16:33
  • 1
    I'm going to guess this is a duplicate of https://stackoverflow.com/q/39044887/5325862 and https://stackoverflow.com/q/44115667/5325862, but it's hard to know exactly without a clear example. [See here](https://stackoverflow.com/q/5963269/5325862) on making this reproducible – camille Aug 16 '21 at 16:43
  • You do still have to use the `if_else`, ... something like `Enterdateofexam2 = if_else(str_detect(Enterdateofexam2, "\\d"), paste0("0", Enterdateofexam2, ".00"), Enterdateofexam2)`. If it applies to all your obs, then the issue is with your `if` condition, but as said we can't possibly help more with only the example of `"1"` as input. – Gregor Thomas Aug 17 '21 at 00:56

1 Answers1

0

We can use sprintf from base R

sprintf("%05.2f", 1)
[1] "01.00"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks akrun, does this also work for character ? –  Aug 16 '21 at 16:42
  • @AaronSong For that `str_pad` can be used. But, if your column is character, convert to numeric with `as.numeric` – akrun Aug 16 '21 at 16:43