Reputation: 1683
I've got a data frame with a date column of the format specified in the title, I would like to know of a simple way to convert them to the standard date format i.e "yyyy-mm-dd" or similar.
So currently my date column is in the format
2012 Week15
2012 Week12
2012 Week16
2012 Week25
2012 Week4
So far I have tried:
df$Date<-gsub("Week","",df$Date)
con.date<-as.Date(df$Date, format="%Y %V")
df<-data.frame(date=con.date,df[,columns excluding the date column])
and
df$Date<-as.Date( df$Date,"%Y %V" )
but these just produce the same date for each year i.e
2012-07-31
2012-07-31
2012-07-31
for some reason.
Any help would be greatly appreciated!
Upvotes: 0
Views: 89
Reputation: 3082
At the moment i wrote a function which only convert a vector with length 1 to your desired output. where i count 01-01 to 01-07 as week 1 etc. And for week 1 i will output the first date of the week.
WeekToDate <- function(Date) {
install.packages("Hmisc")
library(Hmisc)
year <- substr(Date, 1,4)
week <- substring(Date, 10)
date1 <- as.Date(paste(year, "-01-01", sep=""), format="%Y-%m-%d")
Date.list <- seq(date1, date1+yearDays(date1), by="day")
data <- data.frame(Date.list)
data$Week <- as.numeric(format(data$Date.list, "%U"))
data <- data[!duplicated(data$Week),]
output <- data[data$Week==week,]$Date.list
return(output)
}
output would be
> WeekToDate("2013 Week15")
Installing package into ‘D:/Documents/R/win-library/3.0’
(as ‘lib’ is unspecified)
Warning: package ‘Hmisc’ is in use and will not be installed
[1] "2013-04-14"
Upvotes: 1