[英]Obtaining year and month from date column in R
I have a date column where dates look like this: 19940818 19941215 我有一个日期列,其中的日期看起来像这样:19940818 19941215
What is the proper command to extract the year and month from them? 从中提取年和月的正确命令是什么?
If your data is eg 如果您的数据是例如
(df <- data.frame(date = c("19940818", "19941215")))
# date
#1 19940818
#2 19941215
To add two columns, one for month and one for year, you can do 要添加两列,一列代表月份,一列代表年份,您可以
within(df, {
year <- substr(date, 1, 4)
month <- substr(date, 5, 6)
})
# date month year
# 1 19940818 08 1994
# 2 19941215 12 1994
I don't see a need to convert to Date
class here since all you want is a substring of the date column. 我不需要在这里转换为
Date
类,因为您想要的只是date列的子字符串。
Another option is to use extract
from tidyr
. 另一种选择是使用
tidyr
extract
。 Using df
from @Richard Scriven's post 使用@Richard Scriven帖子中的
df
library(tidyr)
extract(df, date, c('year', 'month'), '(.{4})(.{2}).*', remove=FALSE)
# date year month
#1 19940818 1994 08
#2 19941215 1994 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.