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 fine1st
: This is bad; it starts with a number+1
: This is bad; it starts with a special charactervars
: This is fine\^_^
: This is bad; it starts with a special characterfoo
: 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.
<- rnorm(100, mean = 100, sd = 15)
data 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
.
<- rnorm(100, mean = 100, sd = 15)
data <- data
copy
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.
<- 1
mtcars
mtcarsrm(mtcars)
mtcars
Good job! Unfortunately, rm()
cannot help you if you overwrite one of your own objects.