设置月份中的 2 位数字
我有一个 DF
,我想创建一个包含 YEAR 和 MONTH 的列,但为月份设置 2 位数字。请参阅我的代码:
ID <- c(111,222,333,444,555)
DATE <- c(as.Date(c('10/10/2021','12/11/2021','30/12/2021','20/01/2022','25/02/2022') ,"%d/%m/%Y"))
DF_1 <- data.frame(ID, DATE)
添加年份和月份列:
DF_2 <- DF_1 %>%
mutate(YEAR_MONTH = paste(lubridate::year(DATA),
lubridate::month(DATE),
sep = ""))
如您所见,在 ID 444 和 555 中,月份仅显示一位数字。我希望它看起来像这样:
ID <- c(111,222,333,444,555)
DATE <- c(as.Date(c('10/10/2021','12/11/2021','30/12/2021','20/01/2022','25/02/2022') ,"%d/%m/%Y"))
YEAR_MONTH <- c('202110','202111','202112','202201','202202')
DF_3 <- data.frame(ID, DATE, YEAR_MONTH)
我将如何处理这些只显示一位数字的月份?
感激的。
I have a DF
and I would like to create a column with YEAR and MONTH, but setting 2 digits for the month. See my code:
ID <- c(111,222,333,444,555)
DATE <- c(as.Date(c('10/10/2021','12/11/2021','30/12/2021','20/01/2022','25/02/2022') ,"%d/%m/%Y"))
DF_1 <- data.frame(ID, DATE)
Adding the YEAR and MONTH column:
DF_2 <- DF_1 %>%
mutate(YEAR_MONTH = paste(lubridate::year(DATA),
lubridate::month(DATE),
sep = ""))
As you can see, in IDs 444 and 555 the month only presented one digit. I would like it to look like this:
ID <- c(111,222,333,444,555)
DATE <- c(as.Date(c('10/10/2021','12/11/2021','30/12/2021','20/01/2022','25/02/2022') ,"%d/%m/%Y"))
YEAR_MONTH <- c('202110','202111','202112','202201','202202')
DF_3 <- data.frame(ID, DATE, YEAR_MONTH)
How would I go about treating these months that are showing up with just one digit?
Grateful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们可以直接使用
format
进行修改,以返回 4 位年份和 2 位月份,而不是使用lubridate
年/月
。lubridate
返回一个数字/整数值,左侧不能有 0 填充或使用
base R
Instead of using
lubridate
year/month
, we can directly modify withformat
which returns the 4 digit year and 2 digit month.lubridate
returns a numeric/integer value which cannot have 0 as padding on the leftOr using
base R