paljenczy
paljenczy

Reputation: 4899

data.table - subsetting based on variable whose name is a column, too

This may be a bit weird but I frequently face this situation when working with data.table within functions whose argument I am using for filtering.

Imagine you have a variable whose value you want to compare a data.table's column to and do filtering. What if the name of the variable is the same as the column's name?

Example and things I've tried:

DT <- data.table(mtcars)
cyl <- 4
# intended: filter rows where column "cyl" equals the value of variable cyl

# this does not work
DT[cyl == (cyl)]
# this does not work either
DT[cyl == `cyl`]

Upvotes: 9

Views: 1565

Answers (2)

ddunn801
ddunn801

Reputation: 1890

Just specify the scoping:

DT[cyl == globalenv()$cyl]

Upvotes: 6

joel.wilson
joel.wilson

Reputation: 8413

Data.table runs in the environment of the data table itself right, so you might need to specify where you want to get the value from

DT[cyl == get("cyl", envir = parent.frame())]

Upvotes: 9

Related Questions