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)
You have three issues. You need to get rid of
length(y) <2
. Thelength
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, usenchar()
.Second, you don't need to get the number of characters. The
width
argument forstr_pad
sets the expected number of characters in the output. If the input element is already the same number of characters or more aswidth
, it is unchanged.Finally, the usage of
str_pad
is: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 havey
outside the call tostr_pad
. Either puty
as the first argument or specifystring = y
instr_pad
.