Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase number count sequentially from 1 - 365 (366) for every year (leap year)

Tags:

r

I have daily weather data with columns for the day of the month, the month, the year, and the data. But I need to add another column for the day of the year. e.g 1 - 365 (or 366 for leap years).

I'm not much of a programmer at all, I am familiar with seq() e.g. seq(1, 365) But the above would terminate at 365. I need to sequentially increase the number while accounting for the year, so that the sequence starts over every year (and accounts for leap years). In this example, all weather data begin on Jan. 1st. Any ideas/suggestion/pointers much appreciated.

Edit: Example data

example.data <- structure(list(V1 = 1:6, V2 = c(1L, 1L, 1L, 1L, 1L, 1L), 
    V3 = c(1950L, 1950L, 1950L, 1950L, 1950L, 1950L), 
    V4 = c(NA, NA, NA, NA, NA, NA), 
    V5 = c(0, 0, 0, 0, 0, 0)),
    .Names = c("V1", "V2", "V3", "V4", "V5"), row.names = c(NA, 6L), class =                "data.frame")`
like image 987
derelict Avatar asked Sep 18 '25 10:09

derelict


2 Answers

Assuming your dataset is named df, you could construct a date field:

df$date <- as.Date(paste(df$Y, df$m, df$d, sep="-"), "%Y-%m-%d")

And then use the get the %j attribute from that date object:

df$day_of_year <- as.numeric(strftime(df$date, "%j"))
like image 131
devmacrile Avatar answered Sep 20 '25 05:09

devmacrile


Try this code, assuming your "year" column is named "V3":

enter image description here

Edit: More seriously, pasting a picture of your data is a bad idea, see here for how to include your data to make it easier for people to help. Including dput(head(data)) is almost always best.

For your problem, read in your data:

z <- read.csv("test.data.txt", sep="\t", header = FALSE)

Then use dplyr to seq_along() each year:

library(dplyr)
mydat <- z %>% group_by(V3) %>%
               mutate(day = seq_along(V3))

We can verify we got some 366s:

sum(mydat$day == 366)
sum(mydat$day == 365)
like image 28
jeremycg Avatar answered Sep 20 '25 04:09

jeremycg