small_world
small_world

Reputation: 139

How can I append dates to a vector in R?

I created a vector using the vector() function:

actual_dates_vector <- vector()

I then extract the Julian date (eg: 2008201) from a text string:

julian_date<-substr(files[r],10,16)

I then convert the Julian date into YYYY-MM-DD format:

actual_date<-strptime(julian_date, "%Y %j")

This gives me a value like "2009-07-28". I then need to append this to the vector initially created. For which I do this:

actual_dates_vector<-c(actual_dates_vector,actual_date)

But this gives me:

$sec
[1] 0

$min
[1] 0

$hour
[1] 0

$mday
[1] 28

$mon
[1] 6

$year
[1] 109

$wday
[1] 2

$yday
[1] 208

$isdst
[1] 1

I don't understand what's going on. This code actually runs in a loop over multiple dates, so I want the date to be extracted from each date string, converted to YYYY-MM-DD format and appended to the vector. Is there a way to do this?

Thanks.

Upvotes: 1

Views: 4432

Answers (2)

digEmAll
digEmAll

Reputation: 57210

If you prefer a "loop & append" approach, you can do as follows :

# random data to emulate your files 
files <- c("2008281","2009128","2010040")
n_files <- length(files)

# loop & append
actual_dates_vector <- vector()
for(r in 1:n_files){
  dts <- as.POSIXct(files[r],format="%Y%j")

  # convert dts (POSIXct class objects) to character with the desired format
  dts <- format(dts,format="%Y-%m-%d")

  actual_dates_vector <- c(actual_dates_vector,dts)
}

Date objects actually are something else under the hood. As you have seen POSIXlt's are actually lists of the date components while POSIXct's are basically doubles, so they're not what you see when you print them (also the printed format depends on the local settings so you can get different results on differnt machines).
For this reason, since you stated you want a specific representation of the dates (namely YYYY-MM-DD), I suggest you to follow the described approach and store the result into a vector of characters having the desired format.

Upvotes: 2

Justin
Justin

Reputation: 43255

strptime returns a POSIXlt object which is actually a list like you're seeing. If you use as.POSIXct instead of strptime you'll get the result you want.

Also, all the functions you're calling are vectorized so you don't need to do this append strategy, instead you should be able to:

strptime(substr(files, 10 ,16), '%Y %j')

Or something along those lines.

As pointed out in the comments, as.POSIXct calls strptime under the hood.

Upvotes: 2

Related Questions