2

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)
sbac
  • 1,897
  • 1
  • 18
  • 31
  • 1
    Try `str_pad(y, width=2, pad="0")`. You missed to pass the string as first argument. – stefan Oct 20 '20 at 10:17
  • @stefan Even if I do `str_pad(y, width=2, pad="0"` there is also an error. – sbac Oct 20 '20 at 10:19
  • 1
    Simply do `mutate(y = str_pad(y, width=2, pad="0")`. The issue is with length(y). What you want is `str_length(y)`. But in my opinion it is not necessary, as str_pad will only add "0" to strings with length < width – stefan Oct 20 '20 at 10:22
  • @stefan Thank you, it works. I thought that I had to select first strings with length < 2. – sbac Oct 20 '20 at 10:27
  • 1
    You want nchar, not length. – zx8754 Oct 20 '20 at 10:27
  • @zx8754 You're right. Now even my first (redundant) formulation works. – sbac Oct 20 '20 at 10:30
  • No problems, great, let's close this post as "typo/read the manuals". – zx8754 Oct 20 '20 at 10:33

1 Answers1

4

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  
Ben Norris
  • 5,639
  • 2
  • 6
  • 15