4.4 The Basics
4.4.1 R as a calculator
Open RStudio, click on the “Console” pane, type 3 + 3
and press enter. R
displays the result of the calculation.
3 + 3
## [1] 6
+
is called an operator. R has the operators you would expect for for
basic mathematics: +
-
*
/
^
. It also has operators that do
more obscure things.
*
has higher precedence than +
. We can use brackets if necessary
( )
. Try 1+2*3
and (1+2)*3
.
Spaces can be used to make code easier to read.
We can compare with == < > <= >=
. This produces a logical value,
TRUE
or FALSE
. Note the double equals, ==
, for equality
comparison.
2 * 2 == 4
## [1] TRUE
4.4.2 Creating Objects
You can create objects (make assignments) in R with the assignment operator <-
:
<- 3 * 4 x
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.
You will make lots of assignments and <-
is a pain to type. Don’t be
lazy and 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.
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
4.4.3 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 _
. I prefer 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
Others_pRefer.to_RENOUNCEconvention
To inspect an object you can type its name into the console
x
## [1] 12
Make another assignment
<- 20 aVeryLongAssignmentNameForAVariable
To inspect this object, try out RStudio’s completion facility: type
“aVery,” press TAB
, add characters until you have a unique prefix, then
press return.
Assume you made a mistake, aVeryLongAssignmentNameForAVariable
should have value 30 not 20. Use another keyboard shortcut to help you fix it.
Type aVery
then press Cmd/Ctrl + ↑
. That will list all the commands
you’ve typed that start those letters. Use the arrow keys to navigate,
then press enter to retype the command. Change 20 to 30 and rerun.