lundi 13 avril 2020

If else statements for dates in R

Hi I am trying to create a new column in my data frame that follows Boolean true false logic.

What I want to say is " if 'SightDate' between 7-15 and 2-15 return TRUE 1 else FALSE [0]" but can't seem to find the syntax for date functions in r. This is what I have so far.

#convert SightDate to Month-Day
sightingsData$SightMonthDay <- strptime(as.character(sightingsData$SightDate), "%m/%d/%Y")
sightingsData$SightMonthDay <- format.Date(sightingsData$SightMonthDay, "%m-%d")

#Get whether or not sighting occured during the proposed work period
startWork <- as.Date("07-15", format = "%m-%d")
endWork <- as.Date("02-15", format = "%m-%d")

sightingsData$WorkPeriod = if (sightingsData$SightMonthDay <= startWork & SightMonthDay >= endWork, 1,)

And I get the following error:

Error: unexpected ',' in "sightingsData$WorkPeriod = if (sightingsData$SightMonthDay <= startWork & SightMonthDay >= endWork,"

I'm not sure why, because when I take out the comma, I instead get "unexpected numeral 1".

Additionally, I am trying to assign seasons to my data using a function that I found on a forum. But I'm struggling with date assignments in R and can't seem to make sense of it. I want to be able to contain the seasons assignment into a new column titled "SightSeason" or something like that.

sightingsData$sightSeason <- getSeason(sightingsData$SightMonthDay)

But can't seem to see where it is that I would account for that in the function below...before or after I convert my sightingsData$SightData to 2016 values or after. This makes me hesitant, and I wonder if I should create an intermediate column in which I can store the conversion of my sightingsData$SightDate to 2016 values -- something like, sightingsData$2016Sight so that I don't permanently alter my df. I'm not really clear on this. I apologize for rambling, but I'm not sure how to clarify my issues. Anywho, this is the "get seasons function":

### Assign SightMonthDay to Season using 2016 Season Data
getSeason <- function(DATES)
  WS <- as.Date("2016-12-21", format = "%Y-%m-%d") # Winter Solstice
  SE <- as.Date("2016-3-19",  format = "%Y-%m-%d") # Spring Equinox
  SS <- as.Date("2016-6-20",  format = "%Y-%m-%d") # Summer Solstice
  FE <- as.Date("2016-9-22",  format = "%Y-%m-%d") # Fall Equinox

# Convert dates from any year to 2016 dates
d <- as.Date(strftime(DATES, format="2016-%m-%d"))

ifelse (d >= WS | d < SE, "Winter",
        ifelse (d >= SE & d < SS, "Spring",
                ifelse (d >= SS & d < FE, "Summer", "Fall")))

Any insight as to how I can apply that function, or if you know of a different way to assign seasons to my dataset that would be much appreciated! To clarify, I'm using 2016 because it was the last leap year for which there is complete solstice and equinox data.

This is a screenshot of a bit of my df, it has a total of 23585 observations.

Thank you for your time!

Aucun commentaire:

Enregistrer un commentaire