Changes inside a function sometimes leak outside, sometimes not

Open
#5,330 7 comments 0 reactions 0 assignees View on GitHub

@OfekShilon is already working on this.

Since May 6, 2021.

  • #4978 by @OfekShilon — open

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
r
Domain
data

Research direction

Start with the reproducible R example in the issue and compare the behavior of f1 and f2 when setDT() is called inside each function. Review linked pull request #4978 for the existing work. Done should establish and implement a consistent, clearly documented rule for whether these by-reference changes affect the external data.frame.

Written by the indexing model from the issue text.

Description

by-reference

Hello
After much work I was able to locate my problem to a small example:

library(data.table)

dat <- data.frame(col1=c(1,2), col2=c(3,4))

f1 <- function(d) { setDT(d); d[TRUE,   col2:=c(5,6)] }
f2 <- function(d) { setDT(d); d[col1<3, col2:=c(5,6)] }

f1(dat)
dat   # not changed:
#    col1 col2
# 1:    1    3
# 2:    2    4

f2(dat)
dat    # changed:
#    col1 col2
# 1:    1    5
# 2:    2    6

I read that data.table operations are by reference, but not sure what that means when a data.frame becomes a data.table inside a function. Are changes to this new born data.table supposed to apply to the external copy or not?
Either way I hope one of those can be done in all cases, otherwise it is very confusing.

Thank you very much for your good package!

# Output of sessionInfo()

sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 22000)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C LC_TIME=English_United States.1252

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] data.table_1.14.2

loaded via a namespace (and not attached):
[1] compiler_4.1.2 tools_4.1.2

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.