简体   繁体   English

将函数放入数据框

[英]Putting functions into a data frame

It seems possible to assign a vector of functions in R like this: 似乎可以在R中分配一个函数向量,如下所示:

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

so that they can be invoked like this (for example): F[[1]]() . 这样就可以像这样调用它们:(例如) 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 as.data.frame.default(x [[i]],可选= TRUE)中的错误:无法将类““ function”“强制转换为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 do.call() to use the functions: 然后使用do.call()使用以下功能:

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() ( ie as.data.frame.function() ) but can't find it. 问题似乎是R视对象为函数的类,为as.data.frame() as.data.frame.function() )查找适当的方法,但找不到它。 That causes a call to as.data.frame.default() which pretty must is a wrapper for a stop() call with the message you reported. 这将导致对as.data.frame.default()的调用,该调用必须是对带有您报告的消息的stop()调用的包装。

In short, they just seem not to have implemented it for that class. 简而言之,他们似乎只是没有为该课程实施它。

While you can't put a function or other object directly into a data.frame, you can make it work if you go via a matrix. 虽然不能将函数或其他对象直接放入data.frame中,但如果通过矩阵,则可以使其起作用。

foo <- function() {print("qux")}
m <- matrix(c("bar", foo), nrow=1, ncol=2)
df <- data.frame(m)
df$X2[[1]]()

Yields: 产量:

[1] "qux"

And the contents of df look like: df的内容如下所示:

  X1                                   X2
1 bar function () , {,     print("qux"), }

Quite why this works while the direct path does not, I don't know. 我不知道为什么这在直接路径无效的情况下起作用。 I suspect that doing this in any production code would be a "bad thing". 我怀疑在任何生产代码中这样做都是一件“坏事”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM