2

I have a data.table dt with column names x and y. I also have object y that I need to use to filter some rows in dt using the values in dt$y. Unfortunately, since one of the columns has the same name as the object, I can't make it work. What am I doing wrong? Thank you so much.

library(data.table)
dt <- data.table( x = c(1:4), 
                  y = letters[1:4])
y <- "c"

dt[y == y]
#>    x y
#> 1: 1 a
#> 2: 2 b
#> 3: 3 c
#> 4: 4 d
dt[y == (y)]
#>    x y
#> 1: 1 a
#> 2: 2 b
#> 3: 3 c
#> 4: 4 d
dt[y == ..y]
#> Error in eval(stub[[3L]], x, enclos): object '..y' not found
eval(quote(y))
#> [1] "c"
dt[y == eval(quote(y))]
#>    x y
#> 1: 1 a
#> 2: 2 b
#> 3: 3 c
#> 4: 4 d

Created on 2021-04-12 by the reprex package (v2.0.0)

PS: I apologize if this question has been asked somewhere else. I searched for an answer, but I could not find it.

1
  • I agree with sindri_baldur that you could use get, but I just don't see why this would be necessary. I suspect your actual problem is a bit different. Perhaps you could explain further? Commented Apr 12, 2021 at 14:24

1 Answer 1

2

You could use get() and the env argument:

dt[y == get('y', env = -2)]
#    x y
# 1: 3 c

Beware this makes certain assumptions about your setup. If your y is defined in the global environment as in your example, then a safer solution (as suggested by Ian Campell) would be:

dt[y == get('y', env = globalenv())]
Sign up to request clarification or add additional context in comments.

1 Comment

Might be a bit safer to use globalenv() in place of -2. It could get messy if there are functions inside I.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.