本文介绍了dplyr:取消选择列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何取消选择自写函数的 ... 自变量中给出的列。 (我还需要在另一点选择列,因此只需在 ... 中用-指定列即可不能解决我的问题。)

How can I deselect columns given in the ... argument of a self written function. (I also need to select the columns at another point, so just specifying the columns with - in ... does not solve my problem.)

任何解决方案都很简单,选择 -helpers,操作了 或表达式,...

Any soltions are apreciated, select-helpers, manipulating quosures or expressions, ...

# very simple example data
test <- data.frame(a=1:3, b=1:3, c=1:3)

# function skeleton
testfun <- function(x, ...){
  y <- select(x, ...)
  z <- select(x, -...) # does of course not work like this
  return(list(y, z))   # just as an example
}

# calling the function to select different columns
testfun(test, a)
testfun(test, a, b)


推荐答案

这些最简单的解决方案是选择正列,然后比较名称以找出要删除的列,如。

These easiest solution would be to select the positive columns, and then compare names to figure out which columns to drop, as in this answer.

去rk直接显示在点上,

To work on the dots directly,


  1. 我们将把它们捕获在一个数量清单中( quos )。

  2. 取消引号并使用 UQS 拼接点作为正选择。

  3. c()内执行相同的操作,以便我们有一个选择向量。

  4. 取反向量来执行否定选择。

  1. We will capture them in a list of quosures (quos).
  2. Unquote and splice the dots in with UQS for the positive selection.
  3. Do the same thing inside of c() so that we have a vector of selection.
  4. Negate that vector to do the negative selection.

这是(3)和(4)描述的变换。

This is the transformation described by (3) and (4).

library(dplyr)
dots <- quos(a, b)
quos(-c(UQS(dots)))
#> [[1]]
#> <quosure: frame>
#> ~-c(~a, ~b)
#>
#> attr(,"class")
#> [1] "quosures"

那么完整的解决方案就是

The full solution then would be

test <- data.frame(a = 1:3, b = 1:3, c = 1:3)

# function skeleton
testfun <- function(x, ...) {
  dots <- quos(...)
  y <- select(x, UQS(dots))
  z <- select(x, -c(UQS(dots)))
  return(list(y, z))
}

testfun(test, a)
#> [[1]]
#>   a
#> 1 1
#> 2 2
#> 3 3
#>
#> [[2]]
#>   b c
#> 1 1 1
#> 2 2 2
#> 3 3 3

testfun(test, a, b)
#> [[1]]
#>   a b
#> 1 1 1
#> 2 2 2
#> 3 3 3
#>
#> [[2]]
#>   c
#> 1 1
#> 2 2
#> 3 3

选择助手的测试。

testfun(test, starts_with("b"), one_of("c"))
#> [[1]]
#>   b c
#> 1 1 1
#> 2 2 2
#> 3 3 3
#>
#> [[2]]
#>   a
#> 1 1
#> 2 2
#> 3 3

这篇关于dplyr:取消选择列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:00
查看更多