I often want to subset a data.table using a variable that is also a column name in the data.table. For example, imagine I have a data.table with a column called "sex". I also have a variable "sex" defined in my environment (e.g., sex = "male"). If I want to subset the data.table using my sex variable, dt[sex==sex] returns all rows in the data.table because data.table thinks I'm comparing the "sex" column to itself.
Is there a way to tell data.table that I'm using a variable outside of the scope of the column names? I currently have a hacky workaround for this (see below), but there must be a more elegant solution.
library(data.table)
subset_metadata = function(sex){
.sex = sex # hacky workaround
meta = data.table(sex=c("male","female","female","male","male"),
group=c("1w","2w","1w","2w","2w"),
var=rnorm(5))
meta = meta[sex == .sex]
return(meta)
}
subset_metadata("male")