adv12 adv12 - 1 month ago 6
R Question

Subset based on variable column name

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.

Answer

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.