[R] for loop problem

R. Michael Weylandt michael.weylandt at gmail.com
Tue May 1 02:04:25 CEST 2012


Perhaps this is easier: convert your data to Date objects and use the
yday (year day) function from the lubridate package:

i.e., something like this:

jd <- apply(DAT, 1, function(x) as.Date(paste(x, collapse = " "),
format = "%Y %m %d")
# Just a guess you might have to debug it a little

yday(jd)

It will also be generally easier to use proper Date objects in R anyways :-)

Hope this helps,

Michael

On Mon, Apr 30, 2012 at 7:57 PM, Schreiber, Stefan
<Stefan.Schreiber at ales.ualberta.ca> wrote:
> Hi all,
>
> I was wondering if you can help me with the following situation:
>
> I have a data frame that includes weather station data for 30 years in
> the form:
>
> YEAR, MONTH, DAY, TEMP
> 1970, 01, 01, -15
> ...
> 1999, 12, 31, -21
>
> I would like to add another variable "JULIAN" that assigns the integers
> 1 to 365 (and 1 to 366 for leap years) for each day of a year over
> multiple years.
>
> Here is what I came up with:
>
> counter<-1
>
> for(i in 1:12){
> for (j in 1:31){
>
> df$JULIAN[df$MONTH==i & stn$DAY==j]<- counter
> counter<-counter+1
> }
> }
>
> R does it exactly what I told it to but I am not satisfied with it since
> it doesn't stop assigning the integers when months have 28, 29 or 30
> days. For instance on Feb-28 JULIAN is 59 and on March-1 it's 64, as
> opposed to be 60.
>
> I am assuming it must be an ifelse statement, and I was messing around
> with it already but without success.
>
> I guess I am missing some vocabulary here and hope someone can give me
> some pointers.
>
> Thanks,
> Stefan
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list