Museful Museful - 2 months ago 5x
R Question

Putting functions into a data frame

It seems possible to assign a vector of functions in R like this:

F <- c(function(){return(0)},function(){return(1)})

so that they can be invoked like this (for example):

This gave me the impression I could do this:

DF <- data.frame(F=c(function(){return(0)}))

which results in the following error

Error in[[i]], optional = TRUE) : cannot
coerce class ""function"" to a data.frame

Does this mean it is not possible to put functions into a data frame? Or am I doing something wrong?


No, you cannot directly put a function into a data-frame.

You can, however, define the functions beforehand and put their names in the data frame.

foo <- function(bar) { return( 2 + bar ) }
foo2 <- function(bar) { return( 2 * bar ) }
df <- data.frame(c('foo', 'foo2'), stringsAsFactors = FALSE)

Then use to use the functions:[1, 1], list(4))
# 6[2, 1], list(4))
# 8


The above work around will work as long as you have a named function.

The issue seems to be that R see's the class of the object as a function, looks up the appropriate method for (i.e. but can't find it. That causes a call to which pretty must is a wrapper for a stop() call with the message you reported.

In short, they just seem not to have implemented it for that class.