Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to divide a date column in two columns only

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading