data.table evaluation skips function scope when using parent.frame()

Open
#6,933 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
r
Domain
data

Research direction

Start with the [.data.table evaluation entry point and reproduce the minimal examples comparing parent.frame() with data.frame behavior. Determine whether the skipped function frame is intentional; if so, update the ?data.table documentation to describe evaluation frames, otherwise investigate the frame handling causing the discrepancy.

Written by the indexing model from the issue text.

Description

scoping

When evaluating expressions inside [.data.table, the expected scoping behavior seems to break. parent.frame() inside a data.table call does not point one frame up to the function’s environment as expected. Instead, it skips over the function frame and lands higher up the call stack. Note, that parent.frame defaults to parent.frame(n = 1).

Minimal example:

> DT <- data.table(g=1:10, reg=rep(5:8, length.out=10))
> DF <- as.data.frame(DT)
> reg <- 7
> (\() {reg <- 8; DF[DF$reg == get('reg', envir=environment()), ]})()
  g reg
4 4   8
8 8   8
> (\() {reg <- 8; DT[reg == get('reg', envir=environment())][]})()
        g   reg
    <int> <int>
 1:     1     5
 2:     2     6
 3:     3     7
 4:     4     8
 5:     5     5
 6:     6     6
 7:     7     7
 8:     8     8
 9:     9     5
10:    10     6
> (\() {reg <- 8; DT[reg == get('reg', envir=parent.frame())][]})()
       g   reg
   <int> <int>
1:     3     7
2:     7     7

Problem:
We expect parent.frame() to move one level up—the function’s environment—but inside [.data.table, it skips that frame, behaving differently than expected and differently from data.frame behavior.

Question:
Is this frame skipping intended? If yes, could this be documented more explicitly in ?data.table regarding evaluation frames?

Also see: related SO post. This arose as a follow-up problem to data.table issue #4958.

Dominant language
R
Stars
3.9k
Forks
1.1k
Avg merge
14h 4m
Merged PRs (30d)
4

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from Rdatatable/data.table

All issues in Rdatatable/data.table

Similar issues

More R issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.