0

I am trying to convert my date and time to a format that R recognsied to sort my data. I have a code that has worked with previous datasets but here I cannot find for the life of me why it doesn't work. It might be something simple but I am getting v. frustrated This is a code I am trying to run on my dataset named DataLHB:

head(DataLHB)
        date_hour month_num animal_id   name sex Receiver detection_count presence_flag
       1 2009060912         6        42 Ellama   F   101739               1             1
       2 2009060912         6       224  Pokey   F       NA               0             0
       3 2009060913         6        42 Ellama   F   101739               5             1
       4 2009060913         6       224  Pokey   F   101739              11             1     

The code is

sDataLHB <- split(DataLHB, DataLHB$name) ##order the data by individual names
sDataLHB <- lapply(sDataLHB, function(Ind) {
  Ind <- subset(Ind, presence_flag == 1, select = date_hour)
  Ind <- within(Ind, {
   year <- substring(date_hour, 1, 4)
   month <- substring(date_hour, 5, 6)
   day <- substring(date_hour, 7, 8)
   H <- substring(date_hour, 9, 10)
   M <- S <- "00"
   datehour<-paste(paste(year, month, day, sep = "-"),
           paste(H, M, S, sep = ":"))
   RTime <- as.POSIXct(datehour)
   })
  Ind
 })

 **Error in as.POSIXlt.character(x, tz, ...) : character string is not in a standard unambiguous format** 

I tried to add

 as.POSIXct(datehour, format="%Y-%m-%d %H:%M:%S")

but that only gives me warnings

    There were 18 warnings (use warnings() to see them)
    Warning messages:
    1: In `[<-.data.frame`(`*tmp*`, nl, value = structure(list( ... : replacement element 1 has 1 row to replace 0 rows
    2: In `[<-.data.frame`(`*tmp*`, nl, value = structure(list( ... : replacement element 2 has 1 row to replace 0 rows
    3: In `[<-.data.frame`(`*tmp*`, nl, value = structure(list( ... : replacement element 3 has 1 row to replace 0 rows

If anyone can enlighten me I would very much appreciate!

Thanks

  • 2
    Not sure what you need this messy `sDataLHB` for, why not just `as.POSIXct(DataLHB$date_hour, format="%Y%m%d%H")`? – David Arenburg Feb 11 '15 at 21:09
  • I agree with David. When I try just the inner part of your function (running all the regex you have on just the data.frame rather than converting to a list and then sapply'ing), that's working fine -- no errors. – shirewoman2 Feb 11 '15 at 21:36
  • Thanks for the replies. This code is part of a much larger code and I need to create `sDataLHB` for a later part. I have applied this code to another similar dataset before and it worked perfectly, I just don't understand where the bug is in this case with`as.POSIXct`, I was hoping someone had a similar but resolved experience... – manta.stats Feb 13 '15 at 10:04

0 Answers0