0

New to R. I'm trying to conditionally duplicate a function inside another function. I've tried using rlang::duplicate and data.table::copy.

library(rlang)

func1 <- function() {
        print("horg1")
    }
func2 <- function() {
    print("horg2")
}

cond.rename <- function(horg) {
    if (horg=="1") {
            func<-rlang::duplicate(func1)
    }
        
    if (horg=="2") {
            func<-rlang::duplicate(func2)
    }
    
    func
}

cond.rename("1")

This does not work. No function called "func" is created. However, if I run func<-duplicate(func1) outside of a function it will create the function called "func". What am I doing wrong? If it's not obvious, this is drastically simplified from my actual code so if the purpose of the whole thing isn't clear that is why.

pakalla
  • 163
  • 4
  • 10

1 Answers1

1

Your rename_*() function can do one of two things. rename_local() returns a function (not a value) that you can then call.

func1 <- function() {
  print("horg1")
}
func2 <- function() {
  print("horg2")
}

rename_local <- function(horg) {
  if (horg == "1") {
    func <- rlang::duplicate(func1)
  } else if (horg == "2") {
    func <- rlang::duplicate(func2)
  }

  func
}

# Return functions
rename_local("1")
#> function() {
#>   print("horg1")
#> }
rename_local("2")
#> function() {
#>   print("horg2")
#> }

# Return values
rename_local("1")()
#> [1] "horg1"
rename_local("2")()
#> [1] "horg2"

And rename_global() overwrites the function in the global environment. If you want to (re)define a function in the global environment, use <<- instead of <-. This is sometimes called super assignment

rename_global <- function(horg) {
  if (horg == "1") {
    func <<- rlang::duplicate(func1)
  } else if (horg == "2") {
    func <<- rlang::duplicate(func2)
  }
}

# Set global function
rename_global("1")
func
#> function() {
#>   print("horg1")
#> }

Resources for Environments.

wibeasley
  • 5,000
  • 3
  • 34
  • 62
  • Hm, it still doesn't work for me. My end goal is to have a function named "func" in my environment. – pakalla Jan 10 '23 at 00:50
  • Edited my question to clarify I do call in the library first, and other changes of yours – pakalla Jan 10 '23 at 00:51
  • Huh. ...and same error using my exact code? Try restarting the R session? – wibeasley Jan 10 '23 at 00:58
  • I did restart the session and used your exact code. There's no error, it just doesn't create the "func" in my environment. Yours creates a new function called "func"? – pakalla Jan 10 '23 at 01:08
  • I didn't realize you wanted to write to the environment "outside" the rename function. The response now include both approaches. – wibeasley Jan 10 '23 at 01:25