AlexisHaifski
AlexisHaifski

Reputation: 1

Error message stating 'Error: object 'date_Object' not found'

I'm very new to coding and I'm already stumped. I'm working with code that someone else has written, and I need to keep the functionality the same. Here's the error message I keep getting: "Error: object 'date_Object' not found"

Here's the chunk of code I'm trying to run that keeps giving me this error message:

sightdate_to_Date <- function(sightdate)  
date_Object <- mdy(sightdate)
is_wrong <- date_Object > Sys.Date()
date_Object[is_wrong] <- date_Object[is_wrong] - years(100)
date_Object

Please help! I'm not sure why it isn't working since I'm trying to format, not actually changing any data.

Upvotes: 0

Views: 812

Answers (1)

r2evans
r2evans

Reputation: 160447

You need braces around the function declaration. Without them, this is effectively what R sees:

sightdate_to_Date <- function(sightdate) {
  date_Object <- mdy(sightdate)
} # function declaration/definition is complete

is_wrong <- date_Object > Sys.Date()
date_Object[is_wrong] <- date_Object[is_wrong] - years(100)
date_Object

In that context, it should be clear why date_Object is not found. If not ... then it would be good to research "scope" of objects; with a little research, I found https://bookdown.org/rdpeng/rprogdatascience/scoping-rules-of-r.html and https://www.geeksforgeeks.org/scope-of-variable-in-r/ which both seem reasonable. Bottom line, variables created/used inside a function are not available outside the function; the only thing from inside the function that is available outside is the object that is returned, either using the explicit return(.) function (often not needed) or the last expression evaluated in the function. If you look at the return value from your call of sightdate_to_Date(..), you'll notice that it is the return from the only expression, mdt(sightdate), and it is returned because the assignment operators (<- and =) both invisibly return the value assigned.

Ultimately, you need something like:

sightdate_to_Date <- function(sightdate) {
  date_Object <- lubridate::mdy(sightdate)
  is_wrong <- date_Object > Sys.Date()
  date_Object[is_wrong] <- date_Object[is_wrong] - years(100)
  date_Object
}

sightdate_to_Date("2020-02-02") # or whatever object you have

Upvotes: 1

Related Questions