Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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): F[[1]]().

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 as.data.frame.default(x[[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?

like image 693
Museful Avatar asked Feb 13 '26 01:02

Museful


1 Answers

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 do.call() to use the functions:

do.call(df[1, 1], list(4))
# 6

do.call(df[2, 1], list(4))
# 8

EDIT

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 as.data.frame() (i.e. as.data.frame.function()) but can't find it. That causes a call to as.data.frame.default() 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.

like image 53
Christopher Louden Avatar answered Feb 14 '26 13:02

Christopher Louden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!