如何将日期列仅分为两列
How to divide a date column in two columns only
我有一个包含 1 个日期列的数据框:
> head(df$date)
[1] "1952-02-03" "1958-02-08" "1958-02-08" "1958-02-08" "1965-02-07" "1966-03-03"
格式如你所见:“Y%-m%-d%”
我想从这一列创建两列,一列仅包含年份,第二列同时包含月份和日期。
想要输出
year
month_day
1952
02-03
1958
02-08
等等。
我试过这个:
setDT(df)[, c("year", "month_day") :=
c(tstrsplit(date, "-", type.convert = TRUE))]
但我当然会收到此错误消息:Supplied 2 columns to be assigned 3 items.
我完全理解,但我无法在任何地方找到只将日期信息分成两列的语法。
非常感谢。
只需使用 format
获取您想要的日期部分:
df$year <- format(df$date, "%Y")
df$month_day <- format(df$date, "%m-%d")
df
# date year month_day
# 1 1952-02-03 1952 02-03
# 2 1958-02-08 1958 02-08
# 3 1958-02-08 1958 02-08
# 4 1958-02-08 1958 02-08
# 5 1965-02-07 1965 02-07
# 6 1966-03-03 1966 03-03
我有一个包含 1 个日期列的数据框:
> head(df$date)
[1] "1952-02-03" "1958-02-08" "1958-02-08" "1958-02-08" "1965-02-07" "1966-03-03"
格式如你所见:“Y%-m%-d%”
我想从这一列创建两列,一列仅包含年份,第二列同时包含月份和日期。
想要输出
year | month_day |
---|---|
1952 | 02-03 |
1958 | 02-08 |
等等。
我试过这个:
setDT(df)[, c("year", "month_day") :=
c(tstrsplit(date, "-", type.convert = TRUE))]
但我当然会收到此错误消息:Supplied 2 columns to be assigned 3 items.
我完全理解,但我无法在任何地方找到只将日期信息分成两列的语法。
非常感谢。
只需使用 format
获取您想要的日期部分:
df$year <- format(df$date, "%Y")
df$month_day <- format(df$date, "%m-%d")
df
# date year month_day
# 1 1952-02-03 1952 02-03
# 2 1958-02-08 1958 02-08
# 3 1958-02-08 1958 02-08
# 4 1958-02-08 1958 02-08
# 5 1965-02-07 1965 02-07
# 6 1966-03-03 1966 03-03