Dynamically Invoke a Function in R
One way the R programming language has been described is that it is a functional programming language. Whether it would be called this by purists, I don’t know. But part of what this means is that all functions are treated as objects. So you can pass functions around very easily. This might sound strange, but this comes in very handy. One example is when you want to apply a certain function to each element in a given vector. You can use the sapply function, passing as parameters the vector and the function you want to apply to it.
Another nice thing is that you can dynamically invoke functions (reflection) very easily. Let’s say you created a function called “x” and that the purpose of this function was to print “hello, world!”
x = function()
{
print("hello, world!")
}The standard way you would invoke this function would be the following:
x() // hello, world!
But let’s say (for reasons I won’t elaborate on here) that you only had the function name as a character object and wanted to invoke it. You could simply do the following:
"x"() // hello, world!
Is that cool or what!!??!! (though I’m not sure how often it would be useful)