Dplyr: override columns specified

How to deselect the columns specified in the argument ...for your own record. (I also need to select the columns at another point, so just specifying the columns with -in ...will not solve my problem.)

Any corrections are evaluated, select-helpers, manipulating quosuresor 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)
+4
source share
4 answers

This simple solution would be to select the positive columns and then compare the names to find out which columns should be discarded, as in this answer .

To work with points directly,

  • We will write them in the quosures ( quos) list .
  • UQS .
  • c(), .
  • .

, (3) (4).

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

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
+4

purrr::modify_at

library(purrr)
testfun <- function(x, ...){
  y <- select(x, ...)
  z <- modify_at(x,c(...),~NULL)
  return(list(y, z))   # just as an example
}

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

How about this?

testfun <- function(x, ...){
  y <- select(x, ...)
  z <- x[, !names(x) %in% names(y)]
  return(list(y, z))
}
+1
source

You can try:

testfun <- function(x, y, z){
  y1 <- select(x, y)
  z1 <- select(x, -one_of(z)) 
  return(list(y1, z1)) 
}
testfun(test, "a", "b")
[[1]]
  a
1 1
2 2
3 3

[[2]]
  a c
1 1 1
2 2 2
3 3 3

You can also specify more variables using c

testfun(test, c("a", "c"), c("b", "a"))
0
source

Source: https://habr.com/ru/post/1687789/


All Articles