Kind of arguments inheritance in nested functions in R? - r

I'm writing some functions in R and I'm having some issues. Summarizing, inside the function I'm writing, I call another function that I've developed. The 2nd function shares some arguments with the first, how to specify to this 2nd function that has to take the same values for its arguments that the ones in the first function?
first.fx=function(arg1,arg2,arg3,...){
.
.
.
second.fx=function(arg2,arg3,arg4,...){
}
}
The second.fx shares with the first arg2 & arg3. How to inherit these to values to second.fx?

Simply assign the values (which come from the call to first.fx as default parameters in the definition of second.fx:
second.fx <- function(arg2=arg2,arg3=arg3,arg4,...){

You don't need to declare the arguments explicitly in the definition of second.fx. By the magic of lexical scoping, these variables will be found in second.fx's enclosing environment, which is that of first.fx.
first.fx <- function(arg1, arg2, arg3, ...)
{
second.fx <- function(arg4)
{
# values of arg2/3 will be found from first.fx's environment
}
}

Related

function return in R programming language

I need help on returning a value/object from function
noReturnKeyword <- function(){
'noReturnKeyword'
}
justReturnValue <- function(){
returnValue('returnValue')
}
justReturn <- function(){
return('justReturn')
}
When I invoked these functions: noReturnKeyword(), justReturnValue(), justReturn(), I got output as [1] "noReturnKeyword", [1] "returnValue", [1] "justReturn" respectively.
My question is, even though I have not used returnValue or return keywords explicitly in noReturnKeyword() I got the output (I mean the value returned by the function).
So what is the difference in these function noReturnKeyword(), justReturnValue(), justReturn()
What is the difference in these words returnValue('') , return('')? are these one and the same?
When to go for returnValue('') and return('') in R functions ?
In R, according to ?return
If the end of a function is reached without calling return, the value of the last evaluated expression is returned.
return is the explicite way to exit a function and set the value that shall be returned. The advantage is that you can use it anywhere in your function.
If there is no explicit return statement R will return the value of the last evaluated expression
returnValueis only defined in a debugging context. The manual states:
the experimental returnValue() function may be called to obtain the
value about to be returned by the function. Calling this function in
other circumstances will give undefined results.
In other words, you shouldn't use that except in the context of on.exit. It does not even work when you try this.
justReturnValue <- function(){
returnValue('returnValue')
2
}
This function will return 2, not "returnValue". What happened in your example is nothing more than the second approach. R evaluates the last statement which is returnValue() and returns exactly that.
If you use solution 1 or 2 is up to you. I personally prefer the explicit way because I believe it makes the code clearer. But that is more a matter of opinion.

Function (defined by user) as argument of a function

I would like to write a function where one of the argument is a function written by the user.
Specifically, I have something like:
My_function(n,g){
x<-dnorm(n,0,1)
y<-g(x)
return(y)
}
For example, g(x)=x^2 ... but is chosen by the user. Of course, I could directly put g(dnorm(n,0,1)) as argument but I would like the user to write it in terms of x, i.e. g<-x^2 in the example.
How could I do this since the x object is only defined within the function (and not in the arguments)
I can't define the g function beforehand (otherwise, I reckon it's easy). It has to be defined within "My_function" so that the user defines everything he needs in one line.
Why not just declare g as a function with argument?
g=function(x) x^2
My_function=function(n,g){
x<-dnorm(n,0,1)
y<-g(x)
return(y)
}
My_function(1,g)

How to list all the functions signatures in an R file?

Is there an R function that lists all the functions in an R script file along with their arguments?
i.e. an output of the form:
func1(var1, var2)
func2(var4, var10)
.
.
.
func10(varA, varB)
Using [sys.]source has the very undesirable side-effect of executing the source inside the file. At the worst this has security problems, but even “benign” code may simply have unintended side-effects when executed. At best it just takes unnecessary time (and potentially a lot).
It’s actually unnecessary to execute the code, though: it is enough to parse it, and then do some syntactical analysis.
The actual code is trivial:
file_parsed = parse(filename)
functions = Filter(is_function, file_parsed)
function_names = unlist(Map(function_name, functions))
And there you go, function_names contains a vector of function names. Extending this to also list the function arguments is left as an exercise to the reader. Hint: there are two approaches. One is to eval the function definition (now that we know it’s a function definition, this is safe); the other is to “cheat” and just get the list of arguments to the function call.
The implementation of the functions used above is also not particularly hard. There’s probably even something already in R core packages (‘utils’ has a lot of stuff) but since I’m not very familiar with this, I’ve just written them myself:
is_function = function (expr) {
if (! is_assign(expr)) return(FALSE)
value = expr[[3L]]
is.call(value) && as.character(value[[1L]]) == 'function'
}
function_name = function (expr) {
as.character(expr[[2L]])
}
is_assign = function (expr) {
is.call(expr) && as.character(expr[[1L]]) %in% c('=', '<-', 'assign')
}
This correctly recognises function declarations of the forms
f = function (…) …
f <- function (…) …
assign('f', function (…) …)
It won’t work for more complex code, since assignments can be arbitrarily complex and in general are only resolvable by actually executing the code. However, the three forms above probably account for ≫ 99% of all named function definitions in practice.
UPDATE: Please refer to the answer by #Konrad Rudolph instead
You can create a new environment, source your file in that environment and then list the functions in it using lsf.str() e.g.
test.env <- new.env()
sys.source("myfile.R", envir = test.env)
lsf.str(envir=test.env)
rm(test.env)
or if you want to wrap it as a function:
listFunctions <- function(filename) {
temp.env <- new.env()
sys.source(filename, envir = temp.env)
functions <- lsf.str(envir=temp.env)
rm(temp.env)
return(functions)
}

R unary operator overload: risks?

In my continuing quest to avoid using parentheses for some simple commands, I wrote up the following operator to create a new graphics window. My question is: am I at risk of "breaking" anything in R, other than the obvious inability to execute the "not" function on my variable "newdev"?
# function to overload "!" for one purpose only
#this is adapted from the sos package code for "???", credited to Duncan Murdoch.
# Example of how to create a specialized unary operator that doesn't require
# parentheses for its argument. So far as I can tell,
#the only way to do this is to overload an existing function or
# operator which doesn't require parentheses. "?" and "!" meet this requirement.
`!` <- function (e1, e2) {
call <- match.call()
# match.call breaks out each callable function in argument list (which was "??foo" for the sos package "???",
# which allows topicExpr1 to become a list variable w/ callable function "!" (or "?" in sos)
original <- function() {
call[[1]]<-quote(base::`!`)
return(eval(call, parent.frame(2)))
}
# this does preclude my ever having an actual
# variable called "newdev" (or at least trying to create the actual NOT of it)
if(call[[2]] =='newdev') {
windows(4.5,4.5,restoreConsole=T)
}else{
return(original()) # do what "!" is supposed to do
}
}
I executed "!" = function(a){stop("'NOT' is used")} and executed the replications function, which uses the ! operator, and this worked fine. So it looks like it is safe to override "!".
Still you probably want to use classes, which you can do as follows:
# Create your object and set the class
A = 42
class(A) = c("my_class")
# override ! for my_class
"!.my_class" = function(v){
cat("Do wathever you want here. Argument =",v,"\n")
}
# Test ! on A
!A
with
makeActiveBinding
you can replace ls() by e.g LS w/o need of unary operators

Function of two arguments is given only one argument

Suppose I have a function
test <- function(s,t) {
..
}
that requires two arguments.
How can I make it so that it also takes one single argument, i.e. test(t) would return test(t,t)? Thanks in advance.
Because R uses lazy evaluation you can set the default value of the second argument equal to the first argument ...
foo <- function(s,t=s) {
s+t
}
> foo(4)
[1] 8
> foo(4,5)
[1] 9
Setting a default value for an argument is the simplest, but you can also use the missing function inside of the function (in an if statement) to check if an argument was supplied to the function and do something different based on that.

Resources