【问题标题】:input different nchar vector and output into four digit输入不同的 nchar 向量并输出成四位数字
【发布时间】:2017-08-01 19:39:05
【问题描述】:

我想写一个向量随机到一到四位的函数,我想把它全部打印成四位,如果向量中的字符数不够,我想添加0 在那个向量前面。

Input:
x <- 1
x <- 12
x <- 123
x <- 1234

Output:
numb(x)
0001
numb(x)
0012
numb(x)
0123
numb(x)
1234

numb <- function(x) {{if(nchar(x) =4) { print(x) } 
else if (nchar(x) < 4) { y <- 4 - nchar(x) 
paste(nchar(y),x,sep="")}
} 

不知道怎么把1变成0、2变成00、3变成000然后放到粘贴函数里面去。

非常感谢您的帮助。

【问题讨论】:

    标签: r if-statement vector paste


    【解决方案1】:

    我们可以使用sprintf 并指定fmt 有前导零(%04d

    f1 <- function(num){
       sprintf("%04d", num)
    }
    
    f1(c(1, 12, 123, 1234))
    #[1] "0001" "0012" "0123" "1234"
    

    注意:前导零数字属于character 类,而不是numeric/integer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-29
      • 2019-10-16
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      • 1970-01-01
      • 2013-01-08
      相关资源
      最近更新 更多