0

I am using R in RStudio. My dataset comes from a csv file with only 2 variables, namely Date and Price (extract shown below):

Date          Price
2016-12-01     25
2016-12-02     16
2016-12-03     20

and the data goes on till 2017-07-13

Here are R Codes:

test1.data <- read.csv("test1.csv", as.is=TRUE)
test1.data <- transform(test1.data,
                    week = as.POSIXlt(Date)$yday %/% 7 + 1,
                    wday = as.POSIXlt(Date)$wday,
                    year = as.POSIXlt(Date)$year + 1900)

When I execute the codes, I get the following error message:

Error in as.POSIXlt.character(Date) : character string is not in a standard unambiguous format

I had a look at this question: What are the “standard unambiguous date” formats?

I am new to R and I am having a hard time trying to figure out the solution. How do I correct this?

user3115933
  • 4,303
  • 15
  • 54
  • 94
  • There is probably some element that doesn't have a nice format or is associated with a nonexistent date. Maybe try `filter(test1.data, is.na(as.POSIXlt(Date)))` to see. – Frank Jun 13 '17 at 14:38
  • I ran this code and got the following error messages: test1check<-filter(test1.data, is.na(as.POSIXlt(Date))) Error in as.POSIXlt(Date) : object 'Date' not found In addition: Warning message: In data.matrix(data) : NAs introduced by coercion – user3115933 Jun 13 '17 at 14:41
  • D'oh. Okay, guess mine was a bad suggestion... Hm, maybe filter with `!grepl("\\d{4}-\\d{2}-\\d{2}", Date)` instead. Hard to diagnose without a concrete example. General guidance is here: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/28481250#28481250 – Frank Jun 13 '17 at 14:46

1 Answers1

0

Maybe using strftime works for you:

# create Data
test1.data <- data.frame(Date=c('2016-12-01','2016-12-02','2016-12-03'),Price=c(25,16,20))

test1.data <- transform(test1.data,
  week = strftime(Date,format = '%V'),
  wday = strftime(Date,format = '%a'),
  year = strftime(Date,format = '%Y'))

Output:

> test1.data
        Date Price week wday year
1 2016-12-01    25   48  Thu 2016
2 2016-12-02    16   48  Fri 2016
3 2016-12-03    20   48  Sat 2016

In this case I assumed you want week of the year, weekday and year. There's many many more options which you can see at ?strftime

Val
  • 6,585
  • 5
  • 22
  • 52
  • Thanks but I am getting the same error message: Error in as.POSIXlt.character(x, tz = tz) : character string is not in a standard unambiguous format – user3115933 Jun 13 '17 at 15:00
  • 1
    The values in your `Date` column all strictly follow the _YYYY-MM-DD_ scheme? Because that is definitely unambiguous. Did you try and run my code? – Val Jun 13 '17 at 15:05
  • Thanks for pointing me to this. There were some dates which did not follow the yyyy-mm-dd format! – user3115933 Jun 13 '17 at 15:19