Friday, 25 November 2016

Fixing a function

Sometimes R functions are not always doing exactly what you want. In that case you could try to look up the source code for that function paste it into your code and make your modifications there. But sometimes it takes only a small tweak and you want to keep your code as clean as possible. For me this was the case for the vuong test in the pscl package. This function only prints the output, but does not return it. This can easily be fixed by converting the function into text with the ‘deparse’ function. Then the ‘print’ statement can be replaced by a ‘return’ statement by using ‘gsub’. Now the modified text can be turned into a function again by calling ‘eval’ and ‘parse’. With this hack the new function will return the output I need. The code below shows you all described in this post. Go ahead and mutate functions just like that...

require(pscl)
# the vuong test returns NULL. Lines below will modify the function to return the output table:
# Turn the vuong-function into text:
vuong2 <- deparse(vuong)
# remove the current return statement:
vuong2 <- vuong2[!grepl("return", vuong2)]
# instead of printing the output, return it!:
vuong2 <- gsub("print(out)", "return(out)", vuong2, fixed = T)
# now change the text back into an actual function that can be called:
vuong2 <- eval(parse(text = vuong2))
# Now fit some example models to test the modified function:
data("bioChemists", package = "pscl")
fm_zip <- zeroinfl(art ~ . | 1, data = bioChemists)
fm_zinb <- zeroinfl(art ~ . | 1, data = bioChemists, dist = "negbin")
# Test the modified function. Look it returns the test results... Nice...
result <- vuong2(fm_zip, fm_zinb)
print(result)

No comments:

Post a Comment