Chapter 2 Names and values

Learning objectives:

  • To be able to understand distinction between an object and its name
  • With this knowledge, to be able write faster code using less memory
  • To better understand R’s functional programming tools

Using lobstr package here.

library(lobstr)

Quiz

1. How do I create a new column called 3 that contains the sum of 1 and 2?
df <- data.frame(runif(3), runif(3))
names(df) <- c(1, 2)
df
#>           1         2
#> 1 0.9442449 0.1533640
#> 2 0.5366035 0.6029954
#> 3 0.4379617 0.6630377
df$`3` <- df$`1` + df$`2`
df
#>           1         2        3
#> 1 0.9442449 0.1533640 1.097609
#> 2 0.5366035 0.6029954 1.139599
#> 3 0.4379617 0.6630377 1.100999

What makes these names challenging?

You need to use backticks (`) when the name of an object doesn’t start with a a character or ‘.’ [or . followed by a number] (non-syntactic names).

2. How much memory does y occupy?
x <- runif(1e6)
y <- list(x, x, x)

Need to use the lobstr package:

lobstr::obj_size(y)
#> 8.00 MB

Note that if you look in the RStudio Environment or use R base object.size() you actually get a value of 24 MB

object.size(y)
#> 24000224 bytes
3. On which line does a get copied in the following example?
a <- c(1, 5, 3, 2)
b <- a
b[[1]] <- 10

Not until b is modified, the third line