简体   繁体   中英

How to extract 'month' from date given in character form?

I have to extract month from the date format that looks like this: 01-Dec-2016 etc. It is not in the standard date format and R does not read it like a date

I have tried entering coding on R that will read it as date but it gives me an error term

event_date<- as.Date(ACLED_combined$event_date)

Error in charToDate(x) : character string is not in a standard unambiguous format

As final exercise, I have to divide the data into quarters and that depends on the year and month for the event. For that I first need to convert the date into month. Any help will be appreciated!

try using lubridate package.

library(lubridate)

# creates a date object
dmy("01-Dec-2016")

# using date object, you can find the month - you have several options
lubridate::month(dmy("01-Dec-2016"))
lubridate::month(dmy("01-Dec-2016"), label = TRUE)
lubridate::month(dmy("01-Dec-2016"), label = TRUE, abbr = FALSE)

You can convert the string as a datatime object by calling the function as.POSXct(). Then you can use the format() function to just show the month from 1 to 12. Below is an example:

> datestring <- c('01-Dec-2016', '01-Jan-2017','01-Feb-2017')
> datetime <- as.POSIXct(datestring, format = '%d-%b-%Y')
> datetime
[1] "2016-12-01 CST" "2017-01-01 CST" "2017-02-01 CST"
> as.numeric(format(datetime, '%m'))
[1] 12  1  2

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