Pratik
Pratik

Reputation: 141

How can we extract name of the outer function from a sub function?

I have three functions in 'R':

## Inner Function
funcA <- function(A){
  return(A + 1)
}

## Outer Function 1
funcB <- function(B){
  funcA(B)
}

## Outer Function 2
funcC <- function(C){
  funcA(C)
}

What I want to do is -

## Inner Function
funcA <- function(A){
  if (called from funcB()){
    x = 1
  }else if(called from funcC()){
    x = 2
  }
  return(A + x)
}

How can I know which outer function called funcA from inside of funcA?

Thanks for the help in advance.

Upvotes: 2

Views: 73

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270010

This will give a character string containing the name of the calling function:

as.character(sys.calls()[[sys.nframe() - 1]][[1]])

If at all feasible in order to improve modularity I would not do this and instead, pass an argument to funcA which determines how it acts or perhaps it would be possible to use S3 and pass objects of different classes to funcA.

Upvotes: 2

Related Questions