Home > OS >  How to divide a date column in two columns only
How to divide a date column in two columns only

Time:04-05

I have a data frame containing 1 date column:

> head(df$date)
[1] "1952-02-03" "1958-02-08" "1958-02-08" "1958-02-08" "1965-02-07" "1966-03-03"

The format is as you can see: "Y%-m%-d%"

I want to create two columns from this one, one containing the Years only and the second one containing the month and the day together.

Output wanted

year month_day
1952 02-03
1958 02-08

and so on.

I tried this:

setDT(df)[, c("year", "month_day") := 
         c(tstrsplit(date, "-", type.convert = TRUE))]

but of course I get this error message: Supplied 2 columns to be assigned 3 items. which I fully understand but I cannot find anywhere the syntax to split only in two columns the date information.

Many thanks.

CodePudding user response:

Just use format to get the parts of the date you want:

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

  • Related