Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

data.table

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`]
like image 457
paljenczy Avatar asked Nov 16 '16 20:11

paljenczy


People also ask

How do I add data to a table in R?

To add or insert observation/row to an existing Data Frame in R, we use rbind() function. We can add single or multiple observations/rows to a Data Frame in R using rbind() function.


1 Answers

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())]
like image 154
joel.wilson Avatar answered Oct 07 '22 06:10

joel.wilson