1

I have R code that runs a chunk of code that computes columns of statistics for each group in a dataframe. It works as expected when running the code directly in the console with the dataframe.

However, I want to make a package containing this function. When I wrap the original code in a function that takes in a dataframe as an argument and returns the passed in dataframe with the new columns, the resulting columns are not the same.

I was wondering if it has something to do with the scope used in R, but after multiple variations on my code, I can't seem to figure the problem out. I have run into this before as well.

EDIT: I found that when I source the code, it says that it cannot find a function that I have defined above it. This is the region when my code is giving different results because I have wrapped the other function call in a try catch block

Example:

otherFunction <- function(df, ...){
  ...
}

myFunction <- function(df){
  result <- tryCatch({ 
    otherFunction(df, ...)
  }, error = function(e) {
    NA                             # the result is always being set to NA
  })
  return result
}
...
myDf <- ... 
myFunction(myDf)

error: "could not find function "otherFunction""
Richard
  • 89
  • 1
  • 4
  • Please make sure we can actually execute your [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) otherwise it isn't very helpful. – MrFlick Jun 21 '17 at 17:59

1 Answers1

0

The issue is actually with an error in your tryCatch structure (you did not include the parentheses). Because the tryCatch is not structured properly, R cannot create the myFunction object. See modified code below to fix the issue.

otherFunction <- function(df, ...){
  ...
}

myFunction <- function(df){
  result <- tryCatch({
              otherFunction(df, ...)
            }, error = function(err) {
              NA
            })

  return (result)
}

...
myDf <- ... 
myFunction(myDf)
Matt Jewett
  • 3,249
  • 1
  • 14
  • 21
  • Thanks for pointing that out, it was a typo. I had the parentheses in my actual code. There were no errors regarding the syntax part – Richard Jun 21 '17 at 18:56
  • The code I've provided is not producing any errors for me. One other potential cause for your error could be that at the end of your `myFunction` you have the line `return result`, which should actually be `return(result)` – Matt Jewett Jun 21 '17 at 19:01