Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset based on variable column name

Tags:

r

subset

shiny

I'm wondering how to use the subset function if I don't know the name of the column I want to test. The scenario is this: I have a Shiny app where the user can pick a variable on which to filter (subset) the data table. I receive the column name from the webapp as input, and I want to subset based on the value of that column, like so:

subset(myData, THECOLUMN == someValue) 

Except where both THECOLUMN and someValue are variables. Is there a syntax for passing the desired column name as a string?

Seems to want a bareword that is the column name, not a variable that holds the column name.

like image 530
adv12 Avatar asked Jun 12 '13 21:06

adv12


People also ask

How do you subset a Dataframe in R based on column name?

How to subset the data frame (DataFrame) by column value and name in R? By using R base df[] notation, or subset() you can easily subset the R Data Frame (data. frame) by column value or by column name.


2 Answers

Both subset and with are designed for interactive use and warnings against their use within other functions will be found in their help pages. This stems from their strategy of evaluation arguments as expressions within an environment constructed from the names of their data arguments. These column/element names would otherwise not be "objects" in the R-sense.

If THECOLUMN is the name of an object whose value is the name of the column and someValue is the name of an object whose value is the target, then you should use:

dfrm[ dfrm[[THECOLUMN]] == someValue , ] 

The fact that "[[" will evaluate its argument is why it is superior to "$" for programing. If we use joran's example:

 d <- data.frame(x = letters[1:5],y = runif(5))  THECOLUMN= "x"  someValue= "c"  d[ d[[THECOLUMN]] == someValue , ] #   x         y # 3 c 0.7556127 

So in this case all these return the same atomic vector:

d[[ THECOLUMN ]] d[[ 'x' ]] d[ , 'x' ] d[, THECOLUMN ] d$x  # of the three extraction functions: `$`, `[[`, and `[`,      # only `$` is unable to evaluate its argument 
like image 198
IRTFM Avatar answered Sep 19 '22 00:09

IRTFM


This is precisely why subset is a bad tool for anything other than interactive use:

d <- data.frame(x = letters[1:5],y = runif(5)) > d[d[,'x'] == 'c',]   x         y 3 c 0.3080524 

Fundamentally, extracting things in R is built around [. Use it.

like image 35
joran Avatar answered Sep 21 '22 00:09

joran