0

I am trying to do some analysis with a csv file that I have loaded into R. I was doing the following to access specific values via test[[3]][[1]] for example to get the specific value:

test <- read.csv(file = "test.csv")
test <- data.frame(lapply(test, as.character), stringsAsFactors=FALSE)

Otherwise I would have gotten something like this:

> chicago[[3]][[1]]
[1] 08/02/2002 11:00:00 AM
19747 Levels: 01/01/2001 03:49:00 AM 01/01/2001 06:17:00 PM 01/01/2001 12:00:00 AM ... 12/31/2015 11:46:00 AM

Since one column is saving dates I was converting it to POSIXlt.

test[[3]] <- strptime(test[[3]], format='%m/%d/%Y %I:%M:%S %p') 

The values are now being changed as expected, for example:

01/28/2004 06:30:00 PM -> 2004-01-28 18:30:00

Trying to access the values now, I realised though that for example test[[3]][[1]] doesn't give the specific date - instead I get a list that contains every second of each row.

Testing a bit around, I found out that the POSIXit type is a bit "different"; meaning the value mentioned above seems to be some kind of list, being like this:

> unlist(unclass(value))
   sec    min   hour   mday    mon   year   wday   yday  isdst   zone gmtoff 
   "0"    "0"   "11"    "2"    "7"  "102"    "5"  "213"    "1" "CEST"     NA 

So my question is: is there a way to get values like "2004-01-28 18:30:00" instead of a list about the whole column?

mangix
  • 41
  • 4
  • Is there a specific reason to use `POSIXlt` instead of `POSIXct` (which I do prefer for date-times)? – Uwe Nov 13 '16 at 23:10

1 Answers1

3

You are making your life too difficult. You can parse to either Date or Datetime for an entire column. No need for lapply.

You (in general) do not want POSIXlt representation. Look into existing package such as my (relatively recent) anytime package (also on CRAN) which even converts from factor for you -- and does not require explicit format strings, origin values or other holdups.

But as your post does not contain a reproducible example I cannot help with more concrete steps.

Community
  • 1
  • 1
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725