首页 > 解决方案 > R dplyr 列作为变量

问题描述

请你帮助我好吗。

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

这里的例子:

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

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

谢谢你。

约翰

标签: rfilterdplyr

解决方案


使用{{ }}“拥抱”或“双卷曲”运算符稍微简单一些,但它期望变量名 raw vs. 作为字符串。

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

推荐阅读