17
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

R で 9 を "09" みたいにパディングする #rstatsj

Last updated at Posted at 2014-08-13

stringr パッケージを使うと簡単に書ける。

library(stringr)

hour <- as.POSIXlt(Sys.time())$hour # 9
hourStr <- str_sub(paste0("0", hour), start = -2)
print(hourStr)
結果
[1] "09"

dplyr 使って書くと見やすい。

library(dplyr)
library(stringr)

hour <- as.POSIXlt(Sys.time())$hour
hourStr <- paste0("0", hour) %>% str_sub(start = -2)
print(hourStr)

参考:
stringr — Rの文字列をまともな方法で処理する

追記

よく考えたら sprintf() の方が簡単だった。

sprintf("%02d", 9)
sprintf("%02d", 10)
結果
[1] "09"
[1] "10"

追記2

stringr パッケージに str_pad() というものがありました。

str_pad(9, 2, pad=0)
str_pad(10, 2, pad=0)
結果
[1] "09"
[1] "10"
17
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?