How to pass a string to a dplyr filter in a function?

I am looking for a way to pass a string as an input to a function filter_in a dplyr package inside my own function. I created a data frame as follows:

df = data.frame(
    X1 = LETTERS[1:5], 
    X2 = c("apple", "apple", "apple", "banana", "banana")
)

I am looking for a way to write a function in which I can pass an apple or a banana to filter a data frame.

I tried:

filterFruit = function(Data, Fruit){
   retVal = filter_(Data, "X2 == Fruit")
   return(retVal)
}

Then we pass the values:

apple1 = filterFruit(df, "apple")
apple1

This will return an error:

Error: object 'Fruit' not found

I tried several other ways to do this without success, hope someone can help.

Edit:

I realized that I do not need to use filter_ for this operation, since I do not choose which column I am filtering, and I can simply pass the arguments to the filter without quotes. However, this question still matters for the case in which you have:

df = data.frame(
    X1 = LETTERS[1:5], 
    X2 = c("apple", "apple", "apple", "banana", "banana")
    X3 = c("apple", "banana", "apple", banana", "apple")
)

and you need to decide which column (X2 or X3) you want to filter.

+4
2

which, . , retVal.

filterFruit <-  function(Data, column, Fruit){
  idx <- Data[,column]
  retVal <-  which(idx == Fruit)
  fruits_here <- Data[c(retVal), column]
  return(fruits_here)
}
+1

:

library(dplyr)

df = data.frame(
  X1 = LETTERS[1:5], 
  X2 = c("apple", "apple", "apple", "banana", "banana"),
  X3 = c("apple", "banana", "apple", "banana", "apple"), 
  stringsAsFactors=FALSE
)

column_string = "X2"
column_value = "banana"
column_name <- rlang::sym(column_string)

filtered_df <- df %>%
  filter(UQ(column_name) == UQ(column_value))

filtered_df
+3

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


All Articles