Function of two arguments is given only one argument - r

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.

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.

R only specify optional parameters if specified

I have an R function with optional parameters like so:
myFunc <- function(
requiredParam,
optionalParam1 = optionalValue1,
optionalParam2 = optionalValue2,
...
optionalParamN = optionalValueN) {
# implementation
}
I have another function which calls this function and has the necessary parameters stored in a dataframe:
optionalParam1 optionalParam3 optionalParam10
1 "val1" "val2" "val3"
I only want to pass the optional parameters specified in the dataframe. For the others, I want it to use the default values. How can I accomplish this without typing up all permutations of optionalParameters existing/not existing?
Call the function using do.call (not knowing what your data.frame is called I will just assume you have a list or something of the parameters called myParams):
do.call(myFunc, as.list(myParams))
You can also build your function call as a string by parsing your dataframe column names and using paste.
Then, use eval(parse(text="your string"))

detect numeric values in a string

I have to create a function which will detect if there is any non numeric value present in input. For this I have written this code
test<-function(x){
if(is.numeric(x)){
return(T)
}else{
return(F)
}
}
However when I test it with say
> test(a123)
Error in test(a123) : object 'a123' not found
But it works when i use quotes
> test("a123")
[1] FALSE
However I want it working in the first form. Any help on this will be greatly appreciated
test(a123) will not work. You have to store the user input in a object first and then pass it to your function.
Note that with your function test(123) also returns FALSE! (even if you insert deparse(substitute(x)) as suggested in the comments)
A shorter and correct way to perform your test is grep("[^0-9]", x) that returns 1 if the string x contains anything that is not a digit, 0 if not.
If you really want to have your function to work in what you refer to as the 1st form (but I think it is not a good idea as it can't receive any object and doesn't seem to have any use in an R script) :
test<-function(x){
x<-deparse(substitute(x))
grep("[^0-9]",x)
}
> test(123)
integer(0)
> test(a123)
[1] 1

Kind of arguments inheritance in nested functions in 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
}
}

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

Resources