The date in my original Excel file represents the monthly data in the format of "Jan-01". Of course, I can manually convert them to something more useful in the Excel first and then input that into R.
How can I convert such adate into a Date class in R?
Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.
If you want a date
class, use as.Date:
x <- "Jan-01"
as.Date(paste("01-", x, sep = ""), format = "%d-%b-%y")
If you want a POSIXct
class, consider using lubridate
:
library(lubridate)
x <- "Jan-01"
dmy(paste("01-", x , sep =""))
If you want to just rely on base
:
x <- "Jan-01"
as.POSIXct(paste("01-", x, sep = ""), format = "%d-%b-%y")
Edit:
The easiest way is to use the yearmon class in zoo:
require(zoo)
as.yearmon(x, "%b-%y")
#[1] "Jan 2001"
Somewhat longer method:
x="Jan-01"
xs<-strsplit(x, "-")
xd <- as.Date( xs[[1]][2], paste( xs[[1]][1], "01", sep="-"), format="%y-%b-%d")
xd
#[1] "2001-01-01"
If you want to process a string of dates, then you may need to use sapply
if picking the second method to make a vector of years and a vector of months
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With