0
0

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 3 years have passed since last update.

R でドットを変換する方法

Last updated at Posted at 2021-09-10

はじめに

R で文字列にドットが含まれていた場合、それを変換する方法を調べた。

str_replace_all を用いた変換

以下にサンプルコードを示す。

library(stringr)

dt <- "2021.9.10"

この「.」を「/」に変換したい場合、str_replace_allを何も考えずに使うと、

dt_bad <- str_replace_all(dt, pattern=".", replacement="/")
print(dt_bad)
出力
[1] "/////////"

数字と「.」がすべて「/」になってしまった。この場合、patternの中身を「[.]」とすると解決できる。

dt_good1 <- str_replace_all(dt, pattern="[.]", replacement="/")
print(dt_good1)
出力
[1] "2021/9/10"

もしくは「\\.」としても同様の動作をする。

dt_good2 <- str_replace_all(dt, pattern="\\.", replacement="/")
print(dt_good2)
出力
[1] "2021/9/10"

おわりに

これからもRを扱う上で調べたtipsについては、備忘録も兼ねて記事に残していきたいと思う。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?