SophomoreNumberN
SophomoreNumberN

Reputation: 82

How to get and properly identify a function stored in a list in R

I need to be able to add functions in a list and be able to call it using a for() function.

Example:

Sample1 = function(a,c,b) c*3 + b*2 + a*1 +  3
Sample2 = function(d,e,f) d*1 + e*2 + f*3 + 5

sampleRList = list(Sample1,Sample2)

When I call

for(item in sampleRList){
   print(typeof(item))
}

it prints out closure like normal since it is a function, but when I try to get the variables in the function using

foo <- function(x) {
  if(length(x) > 1) {
    res <- lapply(x, foo)
  } else {
      res <- if(is.numeric(x)) x else NA
  }
  na.omit(unlist(res))
}

foo(body(item))

^(sample code) where x would be the current item, it does not return the list containing the variables/numbers.

example of expected result is [1] 1 2 3 4

How do I fix this? Thanks.

foo code taken from here <<

Upvotes: 0

Views: 67

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174476

It's not terribly clear what you are asking here. I think you are saying that you want to extract the multiplicative coefficients from the functions Sample1 and Sample2 using the function foo, but you need to be able to do it if Sample1 and Sample2 are in a list.

In your example, you call foo(body(Ex1)), but you have no object called Ex1, so this code throws an error. If on the other hand you call:

foo(body(sampleRList[[1]]))
#> [1] 3 2 1 3

Then you can see that you retrieve the correct coefficients from Sample1, and to retrieve those from Sample2 you would do:

foo(body(sampleRList[[2]]))
#> [1] 1 2 3 5

If you wanted to get both at the same time you could do:

lapply(sampleRList, function(x) foo(body(x)))
#> [[1]]
#> [1] 3 2 1 3
#>
#> [[2]]
#> [1] 1 2 3 5

Upvotes: 1

Related Questions