我有一个数据集 (假设)
test
:test <- data.frame(x = c(90, 801, 6457, 92727), y = rep("test", 4))
print(test)
x y
1 90 test
2 801 test
3 6457 test
4 92727 test
我想创建一个名为test$z
的变量,它与test$x
相同,不同之处在于test$z
始终是10个字符长,并用零填充空缺。因此,生成的数据框将如下所示:
print(test)
x y z
1 90 test 0000000090
2 801 test 0000000801
3 6457 test 0000006457
4 92727 test 0000092727
我认为以下函数会给我想要的结果:
test$z <- paste0(as.character(rep(0, 10-nchar(as.character(test$x)))), as.character(test$x))
但是在rep
函数中出现以下错误:
在 rep(0, 10 - nchar(as.character(test$x))) 中出错:
times 参数无效
有什么不同的方法可以使用rep
函数或其他解决方案来获得test$z
?
formatC(test$x, flag = '0', digits = 10, width = 10)
: - rawr