1

In the search, I found a lot of questions on how to do this for columns, but not for rows.

# Works just fine:
data = as.data.table(iris)
head(data[Species == 'setosa'])

# I want to do it programatically:
varname = 'Species'
head(data[varname == 'setosa']) # Doesn't work
head(data[(varname) == 'setosa']) # Doesn't work
head(data[(varname) == 'setosa', with = F]) # Doesn't work

Any advice on the correct syntax here would be greatly appreciated.

Zhaochen He
  • 610
  • 4
  • 12
  • also you might find this answer useful: https://stackoverflow.com/questions/24833247/how-can-one-work-fully-generically-in-data-table-in-r-with-column-names-in-varia/54800108#54800108 – jangorecki May 01 '19 at 13:52

1 Answers1

2

We can use get

head(data[get(varname) == 'setosa']) 

or eval(as.name

head(data[eval(as.name(varname)) == 'setosa']) 
akrun
  • 874,273
  • 37
  • 540
  • 662