How to mutate a variable using str_pad in R

1.1k views Asked by At

I want obtain as result for df$y "01", "02", "03", "40h", but I can't understand my error:

    library(tidyverse)
    df <- tibble(x = c(1,2,3,4),
                 y = c("1","2","03","40h"))
    df %>%
      mutate(y = if_else(length(y) < 2, str_pad(width=2, pad="0"), y))
    #> Error: Problem with `mutate()` input `y`.
    #> x argument "string" is missing, with no default
    #> i Input `y` is `if_else(length(y) < 2, str_pad(width = 2, pad = "0"), y)`.
    Created on 2020-10-20 by the reprex package (v0.3.0)
1

There are 1 answers

0
Ben Norris On BEST ANSWER

You have three issues. You need to get rid of length(y) <2. The length function returns the number of elements in a vector, not the number of characters in a string. If you absolutely want to check the number of characters, use nchar().

Second, you don't need to get the number of characters. The width argument for str_pad sets the expected number of characters in the output. If the input element is already the same number of characters or more as width, it is unchanged.

Finally, the usage of str_pad is:

str_pad(string, width, side = c("left", "right", "both"), pad = " ")

The first expected argument is the string. If you don't put the string first, it does not know where to look for it. You have y outside the call to str_pad. Either put y as the first argument or specify string = y in str_pad.

 df %>%
   mutate(y = str_pad(string = y, width = 2, pad = "0")
# A tibble: 4 x 2
      x y    
  <dbl> <chr>
1     1 01   
2     2 02   
3     3 03   
4     4 40h