Create a subset function according to one or more pairs of values ​​for data.frame

How to create a function to use one or more pairs of value pairs (x1, y1; x2, y2; ... as needed) for a subset of a data frame, such as

selection <- function(x1,y1, ...){
               dfselected    <- subset(df, V1 == "x1" & V2 == "y1" 
              ##  MAY OR MAY NOT BE PRESENT ##
                                         | V1 == "x2" & V2 == "y2")
               return(dfselected)
                                  }

I can do this using subset()for one indexing. Example:

df <- data.frame(
        V1 = c(rep("a",5), rep("b",5)),
        V2 = rep(c(1:5),2),
        V3 = c(101:110)
                 )

t

V1 V2  V3
a  1  101
a  2  102
a  3  103
a  4  104
a  5  105
b  1  106
b  2  107
b  3  108
b  4  109
b  5  110

And the subset for the pairs ("a", "3") and ("b", "4") looks like

dfselected <- subset(df, V1 == "a" & V2 == 3 | V1 == "b" & V2 == 4 )

I could not find a similar function. I do not know if I should pass an indefinite number of parameters to the function (the so-called "three points") or use if/else. I am starting to work, so links and examples are also welcome. I basically started with this: http://www.ats.ucla.edu/stat/r/library/intro_function.htm

------------------------------ hadley

selection <- function (x,y){
                            match <- data.frame(
                                               V1 = x,
                                               V2 = y,
                                               stringsAsFactors = FALSE
                                                )
                            return(dplyr::semi_join(df, match))
                           }
+4
2

, -: x, y:

df <- data.frame(
  V1 = c(rep("a",5), rep("b",5)),
  V2 = rep(c(1:5), 2),
  V3 = c(101:110),
  stringsAsFactors = FALSE
)

match <- data.frame(
  V1 = c("a", "b"),
  V2 = c(3L, 4L),
  stringsAsFactors = FALSE
)

library(dplyr)
semi_join(df, match)
+3

- , base R merge().

. , ,

merge(df, match)
#   V1 V2  V3
# 1  a  3 103
# 2  b  4 109
+2

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


All Articles