gpt4 book ai didi

r - 在函数内部使用 dplyr 时出错

转载 作者:行者123 更新时间:2023-12-02 06:22:01 26 4
gpt4 key购买 nike

我正在尝试组合一个函数,该函数从原始数据帧创建子集,然后使用 dplyr 的 SELECT 和 MUTATE 根据宽度和长度的总和给出大/小条目的数量萼片/花瓣。

filter <- function (spp, LENGTH, WIDTH) {
d <- subset (iris, subset=iris$Species == spp) # This part seems to work just fine
large <- d %>%
select (LENGTH, WIDTH) %>% # This is where the problem arises.
mutate (sum = LENGTH + WIDTH)
big_samples <- which(large$sum > 4)
return (length(big_samples))
}

基本上,我希望函数返回大花的数量。但是,当我运行该函数时,出现以下错误 -

filter("virginica", "Sepal.Length", "Sepal.Width")

Error: All select() inputs must resolve to integer column positions.
The following do not:
* LENGTH
* WIDTH

我做错了什么?

最佳答案

您遇到了 NSE/SE 问题,请参阅 the vignette for more info

简单地说,dplyr 使用名称的非标准评估 (NSE),并且将列名称传递到函数中会破坏它,而不使用标准评估 (SE) 版本。

dplyr 函数的 SE 版本以 _ 结尾。您可以看到 select_ 与您的原始参数配合得很好。

但是,使用函数时事情会变得更加复杂。我们可以使用 lazyeval::interp 将大多数函数参数转换为列名称,请参阅下面函数中 mutatemutate_ 调用的转换更一般地说,帮助:?lazyeval::interp

尝试:

filter <- function (spp, LENGTH, WIDTH) {
d <- subset (iris, subset=iris$Species == spp)
large <- d %>%
select_(LENGTH, WIDTH) %>%
mutate_(sum = lazyeval::interp(~X + Y, X = as.name(LENGTH), Y = as.name(WIDTH)))
big_samples <- which(large$sum > 4)
return (length(big_samples))
}

关于r - 在函数内部使用 dplyr 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34186903/

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