Creating seasons from date and time columns.

Hi everyone,

I am trying to create a Season variable from my data set which has a column for Date and a Column for time (which I have made "datetime"). I have two data sets that I am working with at the same time (they are set up in the exact same way they are just from two different field sites). For the LB site the code works perfectly and I get the observations broken up into seasons.

> LB2$datetime<-paste(LB2$DATE,LB2$TIME)
> LB2$datetime<-strptime(LB2$datetime,format="%d/%m/%Y %H:%M")
> LB2$month<-as.numeric(format(LB2$datetime,"%m"))
> LB2$season<-"summer"
> LB2$season[LB2$month>2&LB2$month<5]<-"autumn"
> LB2$season[LB2$month>4&LB2$month<9]<-"winter"
> LB2$season[LB2$month>8&LB2$month<12]<-"spring"
> LB2$season<-factor(LB2$season,levels=c("summer","spring","winter","autumn"))
> summary(LB2$season)
summer spring winter autumn 
  6164   1989  20928  11801 

However when I run the same code for the NG site it doesn't work and classes everything as Summer. I am really stuck as to what I am doing wrong (I am still pretty new to R)

> NG1$datetime<-paste(NG1$DATE,NG1$TIME)
> NG1$datetime<-strptime(NG1$datetime,format="%d/%m/%Y %H:%M")
> NG1$month<-as.numeric(format(NG1$datetime,"%m"))
> NG1$season<-"summer"
> NG1$season[NG1$month>2&NG1$month<5]<-"autumn"
> NG1$season[NG1$month>4&NG1$month<9]<-"winter"
> NG1$season[NG1$month>8&NG1$month<12]<-"spring"
> NG1$season<-factor(NG1$season,levels=c("summer","spring","winter","autumn"))
> summary(NG1$season)
summer spring winter autumn 
 56226      0      0      0

This seems to be related to your specific data set, Can you please share a small part of the data set in a copy-paste friendly format?

In case you don't know how to do it, there are many options, which include:

  1. If you have stored the data set in some R object, dput function is very handy.

  2. In case the data set is in a spreadsheet, check out the datapasta package. Take a look at this link.

I am trying to use the second option (as my data is a pretty giant spreadsheet) but I keep hitting this error:

Error in strrep(" ", char_length - nchar(char_vec)) :
invalid 'times' value

I found looked at a couple of help guides for this error but I keep getting it.

I suspect one of the columns in the NG1 data set is not of the type you expect it to be. What is the result of


Wow. Yes that was absolutely the problem!! In the LB dataset date was DATE but in the NG1 it was Date. When I changed that it worked! R is new to me and I still learning how to troubleshoot without panicking first! Thanks so much for your help!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.