去掉数字月份前面多余的0
我有一个 df
,其中有一列以 character
格式存储日期,我想提取月份。为此,我使用以下内容:
mutate(
Date = as.Date(
str_remove(Timestamp, "_.*")
),
Month = month(
Date,
label = F)
)
但是,十月、十一月和十二月在存储时在月份前面有一个额外的零。 lubridate
库无法识别它。如何调整上面的代码来解决这个问题?这是我的 Timestamp
列:
c("2021-010-01_00h39m", "2021-010-01_01h53m", "2021-010-01_02h36m",
"2021-010-01_10h32m", "2021-010-01_10h34m", "2021-010-01_14h27m"
)
I have a df
with a column which has dates stored in character
format, for which I want to extract the months. For this I use the following:
mutate(
Date = as.Date(
str_remove(Timestamp, "_.*")
),
Month = month(
Date,
label = F)
)
However, the October, November and December are stored with an extra zero in front of the month. The lubridate
library doesn't recognise it. How can I adjust the code above to fix this? This is my Timestamp
column:
c("2021-010-01_00h39m", "2021-010-01_01h53m", "2021-010-01_02h36m",
"2021-010-01_10h32m", "2021-010-01_10h34m", "2021-010-01_14h27m"
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先将值转换为日期并使用
format
从中获取月份。%b
给出缩写的月份名称,您也可以根据您的选择使用%B
或%m
。First convert the values to date and use
format
to get months from it.%b
gives abbreviated month name, you may also use%B
or%m
depending on your choice.一种方法是使用 strsplit 提取第二个元素:
它将返回:
数据:
One way would be use
strsplit
to extract the second element:which will return:
data: