6

I am trying to convert my data into different date format.

e.g from 2010-12-31 to 2010365

I tried code below but it gave me something different (e.g 359 360 361 362 363 364 365). I have my data from year 2000 to 2010.

dayofyear <- strptime(date, format="%Y-%m-%d")$yday + 1

Could somebody help please?

Many thanks.

Tomas
  • 57,621
  • 49
  • 238
  • 373
Sofea
  • 127
  • 1
  • 5

3 Answers3

18

In base r:

format(as.Date('2010-12-31'), format='%Y%j')

Or:

strftime('2010-12-31', format='%Y%j')
Justin
  • 42,475
  • 9
  • 93
  • 111
6
d <- as.POSIXlt("2010-12-31", format="%Y-%m-%d")
d$yday + 1
# 365
paste0(1900 + d$year, d$yday + 1)
# 2010365

Update: to read from txt file:

t <- read.table(file = "file.txt", header = TRUE, sep = ";", dec = ",") 
    # make settings according to file format

Then you can access the column value by t$column_name or t[,column_number], and you replace the "2010-12-31" by one of these expressions and that's it.

Tomas
  • 57,621
  • 49
  • 238
  • 373
  • Thanks @Tomas. Trying to figure out how to call a txt file into the code because all the dates from 2000-01-01 to 2010-12-31 is in a txt file form. By the way, 2010-12-31 should be 2010365. :) – Sofea Nov 26 '13 at 19:43
  • the POSIXlt standard is 0 based indexing rather than 1 based, so 2010-01-01 is the 0th day of the year. – Justin Nov 26 '13 at 19:46
  • @Sofea reading from text file is very easy, updated my answer – Tomas Nov 26 '13 at 19:52
  • Thanks a lot @Tomas. You forgot to edit the second line which should also appear as d$yday+1. I have double check the leap years and all is correct. – Sofea Nov 26 '13 at 20:30
  • Great Sofea, glad to help! – Tomas Nov 26 '13 at 20:57
5
library(lubridate)
date <- ymd("2010-12-31")
paste0(year(date), yday(date))
# [1] "2010365" 
Henrik
  • 65,555
  • 14
  • 143
  • 159
  • 5
    It's possible without installing a new library, see my answer. – Tomas Nov 26 '13 at 19:32
  • @Tomas, Cheers, yes I am aware of that. It's just my personal preferences - I'm very pragmatic when it comes to using non-base packages or not. Sometime speed of execution is most important, sometimes time of writing/remembering the syntax ([see e.g. here](http://stackoverflow.com/questions/10645815/why-are-lubridate-functions-so-slow-when-compared-with-as-posixct/10653798#10653798)). But thanks for reminding me of my (bad) habits ;) – Henrik Nov 26 '13 at 20:47