Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 40 / 68

Shallow copies versus deep copies

This lesson covers the difference between shallow and deep copies in R, with the aim of avoiding bugs caused by unintentionally shared data.

An ordinary R object is copied by value on assignment, but an object built on an environment copies only a reference pointing at the same thing. That is a shallow copy.

In the sample code, make_address() holds its data in an environment, so shallow <- original makes shallow point at the same environment. Changing it with shallow$city <- "Osaka" therefore changes original$city too.

A common early stumble is that most R data structures (vectors, lists) are passed by value while environments alone are passed by reference. Missing that difference makes for surprising bugs.

In professional work, environments are sometimes used deliberately precisely because state should be shared, so it pays to understand the property and choose accordingly.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)