[英]Obtaining year and month from date column in R
我有一個日期列,其中的日期看起來像這樣:19940818 19941215
從中提取年和月的正確命令是什么?
如果您的數據是例如
(df <- data.frame(date = c("19940818", "19941215")))
# date
#1 19940818
#2 19941215
要添加兩列,一列代表月份,一列代表年份,您可以
within(df, {
year <- substr(date, 1, 4)
month <- substr(date, 5, 6)
})
# date month year
# 1 19940818 08 1994
# 2 19941215 12 1994
我不需要在這里轉換為Date
類,因為您想要的只是date列的子字符串。
另一種選擇是使用tidyr
extract
。 使用@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.