I have a data frame that looks like this:
species<-"ABC" ind<-rep(1:4,each=24) hour<-rep(seq(0,23,by=1),4) month<-rep(seq(1,12),8) depth<-runif(length(ind),1,50) df<-data.frame(species,ind,month,hour,depth)
What I would like is to use the column month to specify intervals for each season and return those values in a new column from the same data frame. I was using this code for the seasons, which seems to work fine,
# Classify months into seasons summer<-c(1,2,12) fall<-c(3,4,5) winter<-c(6,7,8) spring<-c(9,10,11) # Create a new column with seasons df$season<-NA for(i in 1:nrow(df)){ if(df$month[i]%in%summer){df$season[i]<-"1-summer"} else if(df$month[i]%in%fall){df$season[i]<-"2-fall"} else if(df$month[i]%in%winter){df$season[i]<-"3-winter"} else if(df$month[i]%in%spring){df$season[i]<-"spring"}
}
However, this loop in already inside of a bigger loop with more complex and bigger data bases. So I was looking for a faster, more efficient approach. The reason that I am using a loop rather than cutting or subsetting my original data frame is because the first loop that I am using is separating and performing analyses on individual animals. The length of resulting data frame varies between animals and one of the problems that I was having is that not all animals were present in all months, so when I was trying to assign seasons inside the loop for animals that were not present on a particular season, then R gave me an error message...