0

Example:

test_fn1 <- function(b,passed=pass){
b*passed}

test_fn2 <- function(a){
pass=10;
print(test_fn1(a))}

test_fn2(2)

It can't find 'pass' so Error:

Error in test_fn1(a) : object 'pass' not found

Is there any way I can pass the local variable created in test_fn2() to test_fn1() as default?

I want to do it by default so that I can use it simply with a vector and lapply(). Example:

test_fn1 <- function(b,passed_vector = pass){
***work with b and passed_vector***}

test_fn2 <- function(a_vector){
pass=***a list of values***;
lapply(a_vector,test_fn1);
}

vector = seq(1:100:10)
test_fn2(vector)
Delta._.43
  • 70
  • 1
  • 8
  • `test_fn1` requires two arguments. Why are you not calling `test_fn1` as `test_fn1(a, pass)` ? – Ronak Shah Jan 23 '21 at 08:43
  • In my program `test_fn1` is only going to be called inside `test_fn2`, using apply(). Where the parameter for `test_fn2` would actually be a list. – Delta._.43 Jan 23 '21 at 09:26

2 Answers2

0

I'm not sure I understand what you want.

Maybe this:

test_fn2 <- function(){
  pass=10;
}

test_fn1 <- function(b,passed=test_fn2()){
  b*passed}
test_fn1(2)
> 20
Leonardo
  • 2,439
  • 33
  • 17
  • 31
  • Not exactly. I edited the question with an example of how exactly I want to use the nested functions. It's not the return value of one function I want to use within the nested one. The code was just a shortened example of my intended use-case – Delta._.43 Jan 23 '21 at 09:32
0

Okay so I figured it out based on this answer here: https://stackoverflow.com/a/6827519/15012262

The solution for the given example then stands as:

test_fn1 <- function(b,passed) b*passed

test_fn2 <- function(a){
pass=10
print(lapply(a,test_fn1,passed=pass))}

test_fn2(2)

[[1]]
[1] 20

I can pass additional variables as parameters with apply() itself. Thank you.

Delta._.43
  • 70
  • 1
  • 8