Objects

Objects

Watch this video:

Object names

You can choose almost any name you like for an object, as long as the name does not begin with a number or a special character like +, -, *, /, ^, !, @, or &.

For instance, check out this list of some possible object names. Some are okay to use; some are invalid:

  • today: This is fine
  • 1st: This is bad; it starts with a number
  • +1: This is bad; it starts with a special character
  • vars: This is fine
  • \^_^: This is bad; it starts with a special character
  • foo: This is fine

Using objects

In the code chunk below, save the results of rnorm(100, mean = 100, sd = 15) to an object named data. Then, on a new line, call the hist() function on data to plot a histogram of the random values.

data <- rnorm(100, mean = 100, sd = 15)
hist(data)

What if?

What do you think would happen if you assigned data to a new object named copy, like this? Run the code and then inspect both data and copy.

data <- rnorm(100, mean = 100, sd = 15)
copy <- data
data
copy

Good job! R saves a copy of the contents in data to copy.

Datasets

Objects provide an easy way to store datasets in R. In fact, R comes with many toy datasets pre-loaded. Examine the contents of mtcars to see a classic toy dataset. Hint: how could you learn more about the mtcars object?

mtcars

Good job! You can learn more about mtcars by examining its help page with ?mtcars.

rm()

What if you accidentally overwrite an object? If that object came with R or one of its packages, you can restore the original version of the object by removing your version with rm(). Run rm() on mtcars below to restore the mtcars data set.

mtcars <- 1
mtcars
rm(mtcars)
mtcars

Good job! Unfortunately, rm() cannot help you if you overwrite one of your own objects.

Next topic