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.