简体   繁体   中英

Converting date column to day of month and month in a new column

I have this kind of data frame

 dat <- read.table(text = " count     date    
                              0    10/05/2012  
                              1    10/05/2013  
                              1    10/05/2014  
                                   ",header = TRUE)

I would like to have a new variable that will contain the following format:

> dat
  count       date DayMonth
1     0 10/05/2012    10-05
2     1 10/05/2013    10-05
3     1 10/05/2014    10-05

I tried some versions of strptime function like dat$DayMonth<-strptime(dat$date, "%d/%m") but got strange resluts. How can I get the desired result

Same solution using the packages lubridate or anydate .

library(lubridate)
dat$DayMonth <- format(dmy(dat$date), "%d-%m")

# dmy stands for day,month,year, can you use ymd etc. 

library(anytime)
dat$DayMonth <- format(anydate(dat$date), "%d-%m")

We can do this with as.Date and format

dat$DayMonth <- format(as.Date(dat$date, "%d/%m/%Y"), "%d-%m")
dat$DayMonth
#[1] "10-05" "10-05" "10-05"

Using strptime converts to POSIXlt/POSIXct class, from which we can change to the format using format

NOTE: No external packages used

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM