首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用R tidyeval获取列名时出错

使用R tidyeval获取列名时出错
EN

Stack Overflow用户
提问于 2019-07-05 00:43:56
回答 1查看 59关注 0票数 0

我正在编写一个通用的查找函数来对tibble执行。当我运行下面的代码时,我得到"Error: object 'x‘not found“

我的实际函数返回一个不同的错误消息,但我认为一些关于这方面的指导会有所帮助。

请参阅下面的代码

代码语言:javascript
复制
library(dplyr)
library(tibble)

fruits <- tibble(
  x = 1:5, 
  y = c("apple", "peach", "pear", "strawberry", "orange")
)

gLookup <- function(datasource, indexColumn, targetValue, lookupColumn){
  datasource %>% 
    filter(indexColumn == targetValue) %>% 
    select(lookupColumn) %>% 
    unlist() %>% 
    unname
}

gLookup(fruits, x, 3, y)

我希望返回"pear“,但得到的却是: Error: object 'x‘not found

EN

回答 1

Stack Overflow用户

发布于 2019-07-05 01:14:13

Writing functions with dplyr is a little complicated,因为它的非标准评估。它背后有a solid framework,但这是一个需要学习的小工作。对于手头的问题,您需要替换并引用传入的列名(使用rlang::enquo),然后在需要使用它们时取消引用(使用!!)。

代码语言:javascript
复制
library(dplyr)

fruits <- tibble::tibble(
    x = 1:5, 
    y = c("apple", "peach", "pear", "strawberry", "orange")
)

gLookup <- function(datasource, indexColumn, targetValue, lookupColumn){
    indexColumn <- enquo(indexColumn)    # substitute and quote
    lookupColumn <- enquo(lookupColumn)

    datasource %>% 
        filter(!!indexColumn == targetValue) %>%    # unquote with !!
        select(!!lookupColumn) %>% 
        unlist() %>% 
        unname
}

gLookup(fruits, x, 3, y)
#> [1] "pear"

如果您使用的是新版本的rlang,则可以使用{{...}}将全部替换、引用和取消引用集于一身

代码语言:javascript
复制
gLookup <- function(datasource, indexColumn, targetValue, lookupColumn){
    datasource %>% 
        filter({{indexColumn}} == targetValue) %>%    # both substitute and quote with `{{...}}`
        select({{lookupColumn}}) %>% 
        unlist() %>% 
        unname
}

gLookup(fruits, x, 3, y)
#> [1] "pear"
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56891842

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档