Subset of data based on dynamic column names

I have a dataset called DF. I want to filter DF based on column 1, so I:

DFb <- subset(DF, Column1 == "ABC")

      

Now I want Column1 to be dynamically defined based on user input, so the user can filter based on any column. Something like that:

Column_Name = 'Column3'  ## User defines this variable
DFb <- subset(DF, as.name(Column_Name) == "ABC")

      

However, this doesn't work. Any suggestions?

+3


source to share


1 answer


Use [[

-subsetting:

DFb <- DF[DF[[Column_Name]] == "ABC",]

      

It's not as elegant as it is subset()

, but it works. subset()

uses "custom evaluation", which is great for interactive use, but makes it difficult when you want to make this second-order link.



The main thing is [[

; you can use subset(DF,DF[[Column_Name]]=="ABC")

instead, the results will be (almost) equivalent ( subset()

automatically discards values ​​where criterion evaluates to NA

...)

You can do it in a package dplyr

, which gives a lot of flexibility in preventing out-of-the-box evaluation, but it's still a bit circular (maybe the best way to do this: I'm not very experienced with dplyr

).

library("dplyr")    ## for filter_()
library("lazyeval") ## for interp()
colname <- "speed"
filter_(cars,interp(~ var == 4, var = as.name(colname)))

      

+4


source







All Articles