在函数内部使用 dplyr 时出错 [英] Error when using dplyr inside of a function

查看:17
本文介绍了在函数内部使用 dplyr 时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to put together a function that creates a subset from my original data frame, and then uses dplyr's SELECT and MUTATE to give me the number of large/small entries, based on the sum of the width and length of sepals/petals.

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)) 
}

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

Basically, I want the function to return the number of large flowers. However, when I run the function I get the following error -

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

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

我做错了什么?

推荐答案

UPDATE:从 dplyr 0.7.0 开始,您可以使用 tidy eval 来完成此操作.

UPDATE: As of dplyr 0.7.0 you can use tidy eval to accomplish this.

参见 http://dplyr.tidyverse.org/articles/programming.html了解更多详情.

filter_big <- function(spp, LENGTH, WIDTH) {
  LENGTH <- enquo(LENGTH)                    # Create quosure
  WIDTH  <- enquo(WIDTH)                     # Create quosure

  iris %>% 
    filter(Species == spp) %>% 
    select(!!LENGTH, !!WIDTH) %>%            # Use !! to unquote the quosure
    mutate(sum = (!!LENGTH) + (!!WIDTH)) %>% # Use !! to unquote the quosure
    filter(sum > 4) %>% 
    nrow()
}

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

> filter_big("virginica", Sepal.Length, Sepal.Width)
[1] 50

这篇关于在函数内部使用 dplyr 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆