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.
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.
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") .
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.
In base r:
format(as.Date('2010-12-31'), format='%Y%j')
Or:
strftime('2010-12-31', format='%Y%j')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With