issue with assignment of eval'd object with by=

Open
#1,857 2 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

Run the self-contained R and data.table example from the issue and confirm that the functions print differently before assignment but become identical in DT$f. Investigate how the expression created by eval and do.call(substitute, ...) is stored during grouped assignment. Done means each row retains its own function and the final uniqueN check distinguishes their results.

Written by the indexing model from the issue text.

Description

programming

I'm creating one function per row based on a "template":

library(data.table)
options(keep.source = FALSE)

u_cdf = function(u, muU, sdU) pnorm(n, muU, sdU)
v_pdf = function(v, muV) dexp(v, 1/muV)

f0 = substitute(function(v) v_pdf * (1 -  u_cdf), list(u_cdf = body(u_cdf), v_pdf = body(v_pdf)))

parnames = 
  setdiff(Reduce(union, lapply(list(u_cdf, v_pdf), function(f) names(formals(f)))), c("u","v"))

DT = data.table(muU = 0:1, sdU = 2:3, muV = 4:5, p = 6:7)

DT[, f :=  {
    f = eval(do.call(substitute, 
        list(f0, c(.SD, list(u = substitute(p - v))))
    ))
    print(f)
    .(.(f))
}, by=1:nrow(DT), .SDcols = parnames]
# function (v) 
# dexp(v, 1/4L) * (1 - pnorm(n, 0L, 2L))
# function (v) 
# dexp(v, 1/5L) * (1 - pnorm(n, 1L, 3L))

That seems fine, but...

# all the functions are the same after assignment
DT$f
# [[1]]
# function (v) 
# dexp(v, 1/5L) * (1 - pnorm(n, 1L, 3L))

# [[2]]
# function (v) 
# dexp(v, 1/5L) * (1 - pnorm(n, 1L, 3L))

# testing by calling each function, since R likes to print funs in an obfuscatory manner
uniqueN(sapply(DT$f, function(f) f(10)))
# [1] 1

For now I'm doing a for loop instead since speed is not a big issue here and I am sick of debugging environments/evaluations/substitutions. Thanks.

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.