How to make matrix elements callable

I want to create a matrix of functions (which I wrote). Then access the elements and call them.

So I have: func1(x)

, func2(y)

, func3(z)

and func4(t)

, which are the four R-functions that I wrote that work fine. They return a number.

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 am getting the following error:

error:attempt to call non-function.

      

Instead of a matrix, if I use a list,

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

      

gives the expected result

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

      

If I do this:

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

      

(I am using R 3.1.1)

+3


source to share


1 answer


When you create non-atomic matrices like these, they basically turn into fancy lists. Similar rules apply to these lists for regular lists when it comes to indexing; namely that [ ]

it will always return a different list, but that it [[ ]]

will retrieve the item without the list wrapper. Do 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 will 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

      

+6


source







All Articles