简体   繁体   中英

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

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

eg from 2010-12-31 to 2010365

I tried code below but it gave me something different (eg 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.

In base r:

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

Or:

strftime('2010-12-31', format='%Y%j')
library(lubridate)
date <- ymd("2010-12-31")
paste0(year(date), yday(date))
# [1] "2010365" 
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM