R:how to stored and change the input using the function - r

I recently study R, but I am not familiar with using the function. I was trying to use a function to modify my initial input like:
x<-c(1,2,3,4,5,5,4)
number_to_words<-function(x){
a<-1
while(a<8){
if(x[a]==1){
as.character(x[a])
x[a]<-"one"
}
else if(x[a]==2){
as.character(x[a])
x[a]<-"two"
}
else if(x[a]==3){
as.character(x[a])
x[a]<-"three"
}
else{
as.character(x[a])
x[a]<-"four"
}
a=a+1
}
return(x)
}
number_to_words(x)
x
but I found out that the value in x hadn't been changed, whether there is a method that I could let each component of x[a] in my function to be modified and stored? like x->f(x)->y but x's value is replaced by y?

The issue you have here is that you are assuming that the function is "call by reference" but R uses "call by value". This basically means that a copy of the arguments you pass into a function is made and it is that copy that you are manipulating inside the function.
The easiest solution in your case is to overwrite x when your function returns
x <- number_to_words(x)

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.

Is it valid to access global variables in R function and how to assign it in a package?

I have a package which provides a script and some functions. Within the script I assign a variable which will be used by the function. This works if the function gets executed within the script but might fail if I just call the function since the variable doesn't exist.
If I use devtools::check() I get warnings, that the variable within the function isn't defined. How can I handle this properly?
Edit
I am thinking about to use get() within the function to assign the variable within the function to get rid of this warnings. So the question is, is myp2 the correct way of doing something like this? Maybe some trycatch to handle errors?
ab <- c(1,2,3)
myp1 <- function() {
print(ab)
return(1)
}
myp2 <- function() {
ab <- get('ab')
print(ab)
return(1)
}
myp1()
myp2()
You could do something like
if(!exists("your variable")){
stop("You have not defined your variable")}
This would check to see if what you are looking for exists. A better practice would be to define the variable in the function and have the default value be the name of the thing for which you are looking.
myp <- function(x) {
print(x)
return(1)
}
ab <- c(1,2,3)
myp(x = ab)
If possible, it would be also better to substitute the script with a function.

R: Function changing print behavior when returning NULL

This question is only for curiosity. My colleague and I were trying to write a function which returns NULL, but doesn't print it.
Before we found return(invisible(NULL)), I tried return({dummy<-NULL}) which works, but only once. After the first evaluation, the functions starts printing again:
test <- function() {
return({x<-NULL})
}
# no printout
test()
# with printout
test()
# with printout
test()
How does this come about?
I think this is due to some older return handling built into R. There are many return functions, withVisible, invisible, etc. When you return an assignment x<-null inside the return function it will not automatically print. If you want an assignment to print...
test <- function() {
withAutoprint(x<-NULL)
}
# with printout this time
test()
# with printout
test()
# with printout
test()
I think this just may be hard coded into the return function, maybe pulling something from this logic below, just a shot in the dark though.
Source: R Documentation
x <- 1
withVisible(x <- 1) # *$visible is FALSE
x
withVisible(x) # *$visible is TRUE
Again if we do not use an expression and simply return a variable or value inside our return function we get automatic printing. The reason I am guessing it returns on a second call has to do with the fact x was already assigned previously.
EDIT: I found this deep into the documentation on auto printing. "Whether the returned value of a top-level R expression is printed is controlled by the global boolean variable R_Visible. This is set (to true or false) on entry to all primitive and internal functions based on the eval column of the table in file src/main/names.c: the appropriate setting can be extracted by the macro PRIMPRINT."(Source)

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)

Catching use of return without parentheses in R

I just tracked down a silly bug in some R code that I had written. The bug was equivalent to this:
brokenEarlyReturn = function(x=TRUE) {
if (x) return # broken with bare return
stop("Should not get here if x is TRUE. x == ", x)
}
brokenEarlyReturn(TRUE)
# Error in brokenEarlyReturn(TRUE) :
# Should not get here if x is TRUE. x == TRUE
The problem is that instead of return() I had just a bare return without the following parentheses. This causes the if statement be roughly equivalent to if (x) constant, where the body is a bareword that performs no action. In this case, the bareword is the definition of the return function itself, and the function continues rather than returning. The correct version would look like this:
workingEarlyReturn = function(x=TRUE) {
if (x) return() # parentheses added to return
stop("Should not get here if x is TRUE. x == ", x)
}
It makes sense that R requires parentheses after return, but as a C programmer I'm likely to occasionally forget to add them. Usually there would be a parsing error if they are omitted, but in this case of a bare return in the body of an if statement there is not.
Assuming I want the ability to put a "guard" statement at the top of a function that will return without a value if some condition is not met, how I can avoid making this error in the future? Or at least, how can I make it easier to track down this error when I do make it? Is there some "expression has no effect" warning that I can turn on?

Resources