问题描述
我想获得df $ y "01","02","03","40h"
的结果,但我无法理解我的错误:
library(tidyverse)
df <- tibble(x = c(1,2,3,4),y = c("1","2","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)
解决方法
您遇到三个问题。您需要摆脱length(y) <2
。 length
函数返回向量中的元素数,而不是字符串中的字符数。如果您绝对要检查字符数,请使用nchar()
。
第二,您不需要获取字符数。 width
的{{1}}参数设置输出中预期的字符数。如果输入元素的字符数已经与str_pad
相同或更多,那么它不变。
最后,width
的用法是:
str_pad
第一个预期参数是字符串。如果您不将str_pad(string,width,side = c("left","right","both"),pad = " ")
放在第一位,它将不知道在哪里寻找。您在string
的通话之外还有y
。要么将str_pad
作为第一个参数,要么在y
中指定string = y
。
str_pad