Question

I have a dataframe named flow with over 17,000 entries which contains daily water quality days for about 50 years. I have a column that has the jday (day of the year) of each entry but now I want to assign each entry a season from 1 to 4 (winter, spring, fall, summer). This is what I have so far:

> for(i in flow){
+   if (flow$jdays[i] <= 80 | flow$jdays[i]>355){
+   flow$season [i] <- 1
+   } else if (flow$jdays [i] > 80 & flow$jdays [i]<= 172){
     flow$season [i] <- 2
+   }
+   else if(flow$jdays [i] > 172 & flow$jdays [i]<= 264){
+     flow$season [i] <- 3
+   }
+   else{
+     flow$season [i] <- 4
+   }
+ }

I keep getting the following message:

Error in if (flow$jdays[i] <= 80 | flow$jdays[i] > 355) { : 
argument is of length zero
Was it helpful?

Solution

this may be better approach,

flow$season<-ifelse(flow$jdays<=80 | flow$jdays>355 ,1,
                   ifelse(flow$jdays<=172,2,
                         ifelse(flow$jdays<=264,3,4)))

OTHER TIPS

This is in error:

for(i in flow){

Change to:

for(in in seq(nrow(flow))){

A vectorized solution using ifelse:

transform(flow, season=
            ifelse (jdays <= 80 | jdays>355, 1,
                ifelse(jdays <= 172,2,
                    ifelse(jdays <= 264,    3,  4))))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top