Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Define a object in a function which is inside another function

I have one function inside another like this:

func2 <- function(x=1) {ko+x+1}
func3= function(l=1){
  ko=2
  func2(2)+l
}
func3(1)

it shows error: Error in func2(2) : object 'ko' not found. Basically I want to use object ko in func2 which will not be define until func3 is called. Is there any fix for this?

like image 924
TDo Avatar asked Jan 24 '26 10:01

TDo


2 Answers

Yes, it can be fixed:

func2 <- function(x=1) {ko+x+1}
func3= function(l=1){
  ko=2
  assign("ko", ko, environment(func2))
  res <- func2(2)+l
  rm("ko", envir = environment(func2))
  res
}
func3(1)
#[1] 6

As you see this is pretty complicated. That's often a sign that you are not following good practice. Good practice would be to pass ko as a parameter:

func2 <- function(x=1, ko) {ko+x+1}
func3= function(l=1){
  ko=2
  func2(2, ko)+l
}
func3(1)
#[1] 6
like image 135
Roland Avatar answered Jan 26 '26 00:01

Roland


You don't really have one function "inside" the other currently (you are just calling a function within a different function). If you did move the one function inside the other function, then this would work

func3 <- function(l=1) {
  func2 <- function(x=1) {ko+x+1}
  ko <- 2
  func2(2)+l
}
func3(1)

Functions retain information about the environment in which they were defined. This is called "lexical scoping" and it's how R operates.

But in general I agree with @Roland that it's better to write functions that have explicit arguments.

like image 28
MrFlick Avatar answered Jan 25 '26 23:01

MrFlick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!