【发布时间】:2016-09-20 20:17:27
【问题描述】:
我有数据集(比如)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$x 的变量test$z,除了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 吗?
【问题讨论】:
-
你可以使用 sprintf。
-
或
formatC(test$x, flag = '0', digits = 10, width = 10)
标签: r