gpt4 book ai didi

r - R 中的匿名函数

转载 作者:行者123 更新时间:2023-12-02 05:30:35 30 4
gpt4 key购买 nike

使用包含数字列 PY 的数据集 w,我可以:

nrow(subset(w, PY==50))

并得到正确答案。但是,如果我尝试创建一个函数:

fxn <- function(dataset, fac, lev){nrow(subset(dataset, fac==lev))}

然后运行

fxn(w, PY, 50)

我收到以下错误:

Error in eval(expr, envir, enclos) : object 'PY' not found

我做错了什么?谢谢。

最佳答案

来自子集的文档:

Warning This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like [, and in particular the non-standard evaluation of argument subset can have unanticipated consequences.

这个相当晦涩的警告在这里得到了很好的解释:Why is `[` better than `subset`?

最后一句话是你不能使用 subset 而不是 interactively ,特别是不能像你正在尝试的那样通过包装器。您应该改用 [:

fxn <- function(dataset, fac, lev) nrow(dataset[dataset[fac] == lev, , drop = FALSE])

或者更简单地说:

fxn <- function(dataset, fac, lev) sum(dataset[fac] == lev)

关于r - R 中的匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12443797/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com