QuantSolo
QuantSolo

Reputation: 429

How to make the elements of a matrix callable functions

I want to make a matrix of functions (that I wrote). Then access them element wise and call.

So I have : func1(x) , func2(y), func3(z) and func4(t) that are four R functions I wrote that work fine.They return numerics.

Now if I do:

a_matrix <- matrix(c(a=func1,b=func2,c=func3,d=func4),2,2)
a_func<-a_matrix[1,1]
a_func(x)

I get the following error:

error:attempt to call non-function.

Instead of matrix if I use list,

a_list<-list(a=func1,b=func2,c=func3,d=func4)
a_func<-list$a
a_func(x)

gives expected result

typeof(list$a)
[1] "closure" 

If I do :

typeof(a_matrix)
[1] "list"
typeof(a_matrix[1,1])
[1] "list"

(am using R 3.1.1)

Upvotes: 3

Views: 93

Answers (1)

MrFlick
MrFlick

Reputation: 206446

When you create non-atomic matrices like that, they are basically made into fancy lists. Similar rules apply to these lists as to regular lists when it comes to indexing; namely that [ ] will always return another list, and [[ ]] will extract the element without the list wrapper. You really want

func1 <- function(x) x+1
func2 <- function(x) x+2
func3 <- function(x) x+3
func4 <- function(x) x+4

a_matrix <- matrix(c(a=func1,b=func2,c=func3,d=func4),2,2)

a_func <- a_matrix[[1,1]]
a_func(5)
# [1] 6

You'd get the same results with your standard list syntax if you did

a_list <- list(a=func1,b=func2,c=func3,d=func4)
a_func <- a_list["a"]
a_func(5)
# Error: could not find function "a_func"
a_func <- a_list[["a"]]
a_func(5)
# [1] 6

Upvotes: 6

Related Questions