I have the following function:
s_c <- function(n, t){
r_num <- runif(1,min=0,max=1)
use <- sample(s[,1],1)
use2 <- subset(s,s[,1]==use,2)
use2 <- as.numeric(use2)
ne_s <- sample(subset(s,s[,2]!=use2,2),1)
Return(use)
if (t>50 & r_num<0.5){
ne_s
}
else
0
}
I would actually like to use the variable created in the function in a command outside the function, so I would like to “return” in the sense of being able to refer to the variable outside the function
Question 2:
What if I would like to do an assignment within the if statement, for example
if (t>50 & r_num<0.5){
s[,4]=use
}
Can this be done?
Although you should probably return the two values as a list, you can affect the parent’s environment quite easily.
Replace this:
with this:
For your edit, you could use the syntax:
Note: The “parent’s environment” is NOT the environment in which the function is called. It is the environment in which the function is defined. It is for this reason that a function in R is known as a closure. Explicitly:
f()will return 0.s_c()is modifying a differentusevariable (in a different environment).