1

I'm trying to filter my data frame using a variable as the column name and another variable as the filter value. I've used filter_ in the past but where only the value i'm looking to filter was variable.

Here's some example code

#Create data frame
Code <- c("A12561", "B12817")
Value <- c(100,200)

df <- data.frame(Code, Value)


#Normal filter - WORKS
filter(df, Code == "A12561")



#Variable for column and value
Col.Var <- "Code"
Test.Val <- "A12561"

#Filter with only the number coming from a variable - WORKS
filter_(df, ~Code == Test.Val)
#Filter_ Returns nothing - DOESN'T WORK
filter_(df, Col.Var == Test.Val)
#Pasting a string - returns an error - DOESN'T WORK
filter_(df, paste(Col.Var, "==", Test.Val))
user1923975
  • 1,389
  • 4
  • 13
  • 29
  • The second option in the top voted answer is one of the things I attempted in the 3 methods listed above but this did not work. My question is slightly different as I'm passing 2 variables, not 1. – user1923975 Jul 25 '16 at 09:26
  • Maybe this is helpful `filter(df,df[,colnames(df) %in% Col.Var,drop=F]==Test.Val)` – user2100721 Jul 25 '16 at 09:38
  • This is NOT a duplicate because you asked about dynamic column name AND value. – abalter Feb 28 '19 at 05:52
  • Hey, I asked the question again and was able to get an answer: https://stackoverflow.com/questions/54919400/dplyr-filter-using-dynamic-column-name-and-dynamic-value/54919698#54919698 – abalter Feb 28 '19 at 07:01

0 Answers0