在以下数据框中,我需要在年月日之间插入“/”:
df <- data.frame (date = c("20220807", "20191017", "20211001"))
date
1 20220807
2 20191017
3 20211001
预期输出:
date
1 2022/08/07
2 2019/10/17
3 2021/10/01
最简单的方法是将日期解析为日期,然后将它们转换为您想要的任何格式:
library(tidyverse)
df |>
mutate(date = as.Date(date, "%Y%m%d")) |>
# if you would prefer the dates remain strings
mutate(date = format(date, "%Y/%m/%d"))
另一种方法,使用 stringr:
mutate(df, date = str_replace(date, "(\\d{4})(\\d{2})(\\d{2})", "\\1/\\2/\\3"))