首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用rlang包解析引文

用rlang包解析引文
EN

Stack Overflow用户
提问于 2018-11-12 23:45:48
回答 1查看 197关注 0票数 3

我希望将单个参数串成两个参数,并在函数的不同部分中使用每个参数。

是否可以使用准引号(!!)或其他rlang函数来完成此操作?

谢谢!

数据:

代码语言:javascript
复制
person <- tibble(id = 1, age = 20)
friends <- tibble(id = c(2, 3, 4, 5), age = c(48, 29, 20, 48))

(非功能)函数:

代码语言:javascript
复制
different_age_friends <- function(condition, person = person, friends = friends ) {

  person <- person
  friends <- friends

  condition <- str_split(condition, " ~ ", simplify = T)
  condition_statement <- condition[1]
  filter_statement <- condition[2]

  if(!!condition_statement) {
    different_age_friends <- friends %>%
      filter(!!filter_statement)
  }

  return(return_same_age_friends)
}

调用:

代码语言:javascript
复制
different_age_friends(condition = "age == 20 ~ age == 48")

期望输出

代码语言:javascript
复制
id age
2  48
5  48
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-13 04:02:10

使用rlang::parse_expr将字符串转换为表达式,使用eval计算字符串。eval()允许您在其第二个参数中为表达式提供上下文,在该参数中,我们向其提供person数据框架。对于filter,上下文已经被理解为%>%管道左侧的数据。

我们处理这两个表达式的另一个不同之处在于,filter()有一个额外的拟商内部层。因为您已经有了一个表达式,所以不需要再次引用它,所以可以使用!!取消引用。

代码语言:javascript
复制
different_age_friends <- function(condition, p = person, f = friends) 
{
  stmts <- str_split(condition, " ~ ")[[1]] %>% map( rlang::parse_expr )

  if( eval(stmts[[1]], p) )         # Effectively: eval(age == 20, person)
    f %>% filter(!!stmts[[2]])      # Effectively: friends %>% filter(age == 48)
  else
    f
}

different_age_friends(condition = "age == 20 ~ age == 48")
# # A tibble: 2 x 2
#      id   age
#   <dbl> <dbl>
# 1     2    48
# 2     5    48

次要注意事项:

  • 当条件为false时,您没有为different_age_friends提供值。我做了一个假设,在这种情况下,整个朋友名单将被退回。
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53271734

复制
相关文章

相似问题

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