【问题标题】:R dplyr column as variableR dplyr 列作为变量
【发布时间】:2021-06-16 03:30:48
【问题描述】:

你能帮帮我吗?

我已经尝试了很多组合,但没有任何效果。

这里是例子:

library(dplyr)

foo <- function(AA,x){
  mn <- make.names(x)
  mn <- enquo(mn)
  filter(AA,mn==min(!!mn))
}

aa <- data.frame(A=c("a","b","c","d"), B.D = c(1,2,1,3))

foo(aa,"B D")

输出是

 Error: Base operators are not defined for quosures.
Do you need to unquote the quosure?

  # Bad:
  myquosure == rhs

  # Good:
  !!myquosure == rhs
Run `rlang::last_error()` to see where the error occurred. 

而不是

filter(aa,B.D==min(B.D))

  A B.D
1 a   1
2 c   1

能否请您帮助我使用我的函数获得所需的输出。

谢谢。

约翰

【问题讨论】:

标签: r filter dplyr


【解决方案1】:

使用{{ }}“拥抱”或“双花”运算符稍微简单一些,但它需要将变量名原始与字符串形式。

foo <- function(AA,x){
  filter(AA, {{ x }} == min({{ x }}))
}


foo(aa, B.D)  # or foo(aa, `B.D`)
  A B.D
1 a   1
2 c   1

【讨论】:

    【解决方案2】:

    转换为symbol 而不是quosure

    foo <- function(AA,x){
       mn <- make.names(x)
        mn <- ensym(mn)
        filter(AA,!!mn==min(!!mn))
     }
    

    -测试

    foo(aa, "B D")
    #  A B.D
    #1 a   1
    #2 c   1
    

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2014-03-04
      相关资源
      最近更新 更多