2 Names and values


We use the development version of lobstr to answer questions regarding the internal representation of R objects.

2.1 Binding basics

  1. Q: Explain the relationship between a, b, c and d in the following code:

    A: a, b, c point to the same object (with the same address in memory). This object has the value 1:10. d points to a different object with the same value.

  2. Q: The following code accesses the mean function in multiple ways. Do they all point to the same underlying function object? Verify with lobstr::obj_addr().

    A: Yes, they point to the same object. We confirm this by inspecting the address of the underlying function object.

  3. Q: By default, base R data import functions, like read.csv(), will automatically convert non-syntactic names to syntactic names. Why might this be problematic? What option allows you to suppress this behaviour?

    A: Column names are often data, and the underlying make.names() transformation is non-invertible, so the default behaviour corrupts data. To avoid this, set check.names = FALSE.

  4. Q: What rules does make.names() use to convert non-syntactic names into syntactic names?

    A: A valid name starts with a letter or a dot (which must not be followed by a number). It also consists of letters, numbers, dots and underscores only ("_" are allowed since R version 1.9.0).

    Three main mechanisms ensure syntactically valid names (see ?make.names):

    Interestingly, some of these transformations are influenced by the current locale (from ?make.names):

    The definition of a letter depends on the current locale, but only ASCII digits are considered to be digits.

  5. Q: I slightly simplified the rules that govern syntactic names. Why is .123e1 not a syntactic name? Read ?make.names for the full details.

    A: .123e1 is not a syntactic name, because it starts with one dot which is followed by a number. This makes it a double, 1.23.

2.2 Copy-on-modify

  1. Q: Why is tracemem(1:10) not useful?

    A: When 1:10 is called an object with an address in memory is created, but it is not bound to a name. Therefore, the object cannot be called or manipulated from R. As no copies will be made, it is not useful to track the object for copying.

  2. Q: Explain why tracemem() shows two copies when you run this code. Hint: carefully look at the difference between this code and the code show earlier in the section.

    A: Initially the vector x has integer type. The replacement call assigns a double to the third element of x, which triggers copy-on-modify.

    We can avoid the copy by sub-assigning an integer instead of a double:

  3. Q: Sketch out the relationship between the following objects:

    A: a contains a reference to an address with the value 1:10. b contains a list of two references to the same address as a. c contains a list of b (containing two references to a), a (containing the same reference again) and a reference pointing to a different address containing the same value (1:10).

  4. Q: What happens when you run this code:

    Draw a picture.

    A: The initial reference tree of x shows, that the name x binds to a list object. This object contains a reference to the integer vector 1:10.

    When x is assigned to an element of itself copy-on-modify takes place and the list is copied to a new address in memory.

    The list object previously bound to x is now referenced in the newly created list object. It is no longer bound to a name. The integer vector is referenced twice.

2.3 Object size

  1. Q: In the following example, why are object.size(y) and obj_size(y) so radically different? Consult the documentation of object.size().

    A: object.size() doesn’t account for shared elements within lists. Therefore, the results differ by a factor of ~ 100.

  2. Q: Take the following list. Why is its size somewhat misleading?

    A: It is somewhat misleading, because all three functions are built-in to R as part of the base and stats packages and hence always available.

    From the following calculations we can see that this applies to about 2400 objects usually loaded by default.

  3. Q: Predict the output of the following code:

    A: In R (on most platforms) a length-0 vector has 48 bytes of overhead:

    A single double takes up an additional 8 bytes of memory:

    So 1 million double should take up 8,000,048 bytes:

    (If you look carefully at the amount of memory occupied by short vectors, you’ll notice that the pattern is actually more complicated. This is to do with how R allocates memory, and is not that important. If you want to know the full details, they’re discussed in the 1st edition of Advanced R: http://adv-r.had.co.nz/memory.html#object-size).

    In b <- list(a, a) both list elements of b contain references to the same memory address, so no additional memory is required for the second list element. The list itself requires 64 bytes, 48 bytes for an empty list and 8 bytes for each element (obj_size(vector("list", 2))). This let’s us predict 8000048 B + 64 B = 8000112 B:

    The list b already contains references to a, so no extra memory is needed for a and the amount of required memory stays the same.

    When we modify the first element of b[[1]] copy-on-modify occurs and the object will have the same size (8000040 bytes) and a new address in memory. So b’s elements don’t share references anymore. Because of this their object sizes add up to the sum of of the two different vectors and the length-2 list: 8000048 B + 8000048 B + 64 B = 16000160 B (16 MB).

    The second element of b still references to the same address as a, so the combined size of a and b is the same as b:

    When we modify the second element of b, this element will also point to a new memory address. This doesn´t affect the size of the list:

    However, as b doesn’t share references with a anymore, the memory usage of the combined objects increases:

2.4 Modify-in-place

  1. Q: Explain why the following code doesn’t create a circular list.

    A: In this situation Copy-on-modify prevents the creation of a circular list. Let’s step through the details as follows:

  2. Q: Wrap the two methods for subtracting medians into two functions, then use the bench package to carefully compare their speeds. How does performance change as the number of columns increase?

    A: First, let’s define a function to create some random data and a function to subtract the median from each column.

    We can then profile the performance, by benchmarking subtact_medians() on data frame- and list-input for a specified number of columns. The functions should both input and output a data frame, so one is going to do a bit more work.

    Then bench package allows us to run our benchmark across a grid of parameters easily. We will use it to slowly increase the number of columns containing random data.

    When working directly with the data frame, the execution time grows quadratically with the number of columns in the input data. This is because (e.g.) the first column must be copied n times, the second column n-1 times, and so on. When working with a list, the execution time increases only linearly.

    Obviously in the long run, linear growth creates shorter run-times, but there is some cost to this strategy - we have to convert between data structures with as.list() and as.data.frame(). This means that the improved approach doesn’t pay off until we get to a data frame that’s ~800 columns wide.

  3. Q: What happens if you attempt to use tracemem() on an environment?

    A: tracemem() cannot be used to mark and trace environments.

    The error occurs because “it is not useful to trace NULL, environments, promises, weak references, or external pointer objects, as these are not duplicated” (see ?tracemem). Environments are always modified in place.