Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update example in Chapter 2.5.1 #1776

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

MatthiasLiew
Copy link

@MatthiasLiew MatthiasLiew commented Jul 30, 2023

When running the example in 2.5.1 that demonstrates the excessive copies that R makes when modifying a data frame in a loop, I noticed that I could not replicate the results on my local machine. I kept getting two duplications per loop instead of three. A search on stackoverflow ratified my local results and I realised that the example in the book was for pre-R v4.0.0 while I was on R v4.2.2. However, I still could not make heads or tails with respect to the explanation of said results.

Section 3.4.4 of the R Language definition provided a clue with the *tmp* variable which is discussed in Chapter 6.8.4 of this book as well. However, upon rewriting and executing the example with an explicit assignment of the *tmp* variable and calling the [[<- function directly, only one copy per loop was made. Upon inspecting the source code of R, I believe I stumbled across the answer when looking at the functions applydefine and SET_TEMPVARLOC_FROM_CAR. It appears that the *tmp* variable is assigned by the internal C code and in this case, a duplicate of the variable to be assigned later (the data frame x) is made.

The second copy is made after the internal generic function [[<- dispatches to [[<-.data.frame which is a normal closure. The book states this accurately.

The changes proposed are of my own research and any mistakes are my own. Please feel free to correct me if I have made any mistakes.

I assign the copyright of this contribution to Hadley Wickham.

@MatthiasLiew MatthiasLiew changed the title Example in Chapter 2.5.1 Update example in Chapter 2.5.1 Jul 31, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant