Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert yyyy-mm-dd to day of the year in R?

Tags:

date

r

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.

like image 351
Sofea Avatar asked Nov 26 '13 19:11

Sofea


People also ask

How do I change date format in R?

To format = , provide a character string (in quotes) that represents the current date format using the special “strptime” abbreviations below. For example, if your character dates are currently in the format “DD/MM/YYYY”, like “24/04/1968”, then you would use format = "%d/%m/%Y" to convert the values into dates.

How do I convert to year in R?

To get the year from a date in R you can use the functions as. POSIXct() and format() . For example, here's how to extract the year from a date: 1) date <- as. POSIXct("02/03/2014 10:41:00", format = "%m/%d/%Y %H:%M:%S) , and 2) format(date, format="%Y") .

How do I convert a date to a date in R?

You can use the as. Date( ) function to convert character data to dates. The format is as. Date(x, "format"), where x is the character data and format gives the appropriate format.


2 Answers

In base r:

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

Or:

strftime('2010-12-31', format='%Y%j')
like image 157
Justin Avatar answered Oct 24 '22 10:10

Justin


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.

like image 29
Tomas Avatar answered Oct 24 '22 09:10

Tomas