4.5 Objects
4.5.1 Creating Objects
When you have certain values, data, plots, etc that you want to work with
You can create objects (make assignments) in R with the assignment operator <-
:
All R statements where you create objects, assignment statements, have the same form:
object_name <- value
When reading that code say “object name gets value” in your head.
<- 3 * 4
x
x
## [1] 12
Once you have an object you can do other calculations with it.
* x x
## [1] 144
Objects vs. Variables
What are known as objects in R are known as variables in many other
programming languages. Depending on the context, object and variable can
have drastically different meanings. However, in this lesson, the two
words are used synonymously. For more information see:
https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Objects
That last example was kind of abstract. So let’s look at a more practical example.
Let’s do some calculations with the population of Maryland. First we can save the population number to an object. We will call it md_pop
because that is short, descriptive, and easy to remember.
<- 6177224 md_pop
What percentage of the Maryland population is over 18? According to the Census Bureau, 78% of the Maryland population is over 18. We can use that to calculate the number of adults in Maryland.
<- .78 * md_pop md_adult_pop
Next, maybe we are interested in how many people have received at least one dose of a COVID-19 vaccine. As of late June 2021 that number is 3.63 million.
<- 3630000 md_vax_pop
Now we can calculate the percentage of the Maryland population that is vaccinated.
<- (md_vax_pop / md_pop) * 100 percent_vax
As more people get vaccinated this can be updated. Let’s say later in the summer we have 4.1 million with at least one dose of the vaccine. We can re-assign the value of md_vax_pop
<- 4100000 md_vax_pop
Then recalculate percent_vax
<- (md_vax_pop / md_pop) * 100 percent_vax
You will make lots of assignments and <-
is a pain to type. Avoid the temptation to use =
: it will work, but it will cause confusion later.
Instead, use RStudio’s keyboard shortcut: Alt + -
(the minus sign).
Notice that RStudio automagically surrounds <-
with spaces, which is a
good code formatting practice. Code is miserable to read on a good day,
so giveyoureyesabreak and use spaces.
Naming Objects
The name for objects must start with a letter, and can only contain
letters, numbers, underscores (_
)and periods (.
). The name of the
object should describe what is being assigned so they typically will be
multiple words. One convention used is snake_case where lowercase
words are separated with _
. Another popular style is camelCase where compound words or phrases are written so that each word or abbreviation in the
middle of the phrase begins with a capital letter, with no intervening
spaces or punctuation and the first letter is lowercase.
thisIsCamelCase
some_use_snake_case
others.use.periods #avoid
Others_pRefer.to_RENOUNCEconvention #avoid