我正在编写一个通用的查找函数来对tibble执行。当我运行下面的代码时,我得到"Error: object 'x‘not found“
我的实际函数返回一个不同的错误消息,但我认为一些关于这方面的指导会有所帮助。
请参阅下面的代码
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
发布于 2019-07-05 01:14:13
Writing functions with dplyr is a little complicated,因为它的非标准评估。它背后有a solid framework,但这是一个需要学习的小工作。对于手头的问题,您需要替换并引用传入的列名(使用rlang::enquo),然后在需要使用它们时取消引用(使用!!)。
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,则可以使用{{...}}将全部替换、引用和取消引用集于一身
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"https://stackoverflow.com/questions/56891842
复制相似问题