Skip to content

get breaks .SDcols #2647

Closed
Closed

Description

@MichaelChirico

This may be related to #2036 and/or #1548. Sorry for the over-long example, the last command is the one that matters:

library(data.table)
iris = data.table(iris)
iris = iris[ , !'Species']
iris[ , (names(iris)) := lapply(.SD, function(x) {
  (x - mean(x))/sd(x)
})]

xnm = c('x1', 'x2', 'x3')
setnames(iris, c('y', xnm))
y = iris$y

iris[ , c('r', 'y') := .(y, NULL)]
all_cor = iris[ , sapply(.SD, cor, r), .SDcols = xnm]
active = names(which.max(abs(all_cor)))
path = seq(0, all_cor[active], length.out = 100L)
cor_path = sapply(path, function(beta) {
  iris[ , { print(length(.SD))
    sapply(.SD, cor, r - beta*get(active))
    }, .SDcols = xnm]
})

Despite explicitly setting .SDcols = xnm (i.e., x1:x3), .SD has picked up r again (as seen from nrow(cor_path) == 4L.

If we replace get(active) with its current value (x2), the code works as expected. The fix of #1548 (to set envir = as.environment(.SD)) doesn't work here.

Activity

  1. jangorecki commented on Mar 22, 2020

    @jangorecki
    Member

    this might be related to evaluation frame in which .SDcols is evaluated, this should be changed to be evaluated in parent.frame rather than data.table frame.

  2. added this to the 1.12.9 milestone on Mar 22, 2020
  3. added
    programming
    on Apr 5, 2020
  4. modified the milestones: 1.13.1, 1.13.3 on Oct 17, 2020
  5. modified the milestones: 1.14.3, on Jul 19, 2022
  6. modified the milestones: , 1.15.1 on Oct 29, 2023
  7. removed this from the 1.16.0 milestone on Nov 6, 2023
  8. MichaelChirico commented on Nov 8, 2026

    @MichaelChirico
    MemberAuthor

    This is fixed on master:

    nrow(cor_path)
    # [1] 3
  9. MichaelChirico commented on Nov 9, 2026

    @MichaelChirico
    MemberAuthor

    From bisection: #3771

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    programming

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions