简体   繁体   中英

How to remove the day from the date and leave only the month and year from a column in a large dataset in r markdown?

I have a large dataset and one of the columns includes dates formatted DD/MM/YYYY and I would like to just have MM/YYYY. Is there a way to apply this to the entire column in the dataset dat$date ?

We can convert to Date class first with as.Date and then use format

dat$date <- format(as.Date(dat$date, "%d/%m/%Y"), "%m/%Y")

Or another option is regex to match the digits ( \\d+ ) from the start ( ^ ) of the string followed by / and replace with blank ( '' )

dat$date <- sub("^\\d+\\/", "", dat$date)

data

dat <- data.frame(date = c('05/10/2015', '15/05/2010'), stringsAsFactors = FALSE)

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