Chapter 3 Language basics
3.1 Assignments, arithmetic operations
There are two types of R
commands: expressions and assignments.
Expression
## [1] -1
Assignments and expressions
## [1] 3
## [1] FALSE
Using ;
we can type two commands on the same line before executing them:
## [1] 1
Some examples of arithmetic and Boolean operators:
## [1] 12
## [1] 4
## [1] 8
## [1] 4
## [1] FALSE
## [1] FALSE
## [1] FALSE
## [1] TRUE
3.2 Mode, length and class
In R, everything is an object. The mode specifies what an object can contain. The main modes are:
numeric
: real numberscharacter
: character stringslogical
: logical values true / falselist
: list, collection of objectsfunction
: function
numeric
,character
, and logical
objects are simple objects that can contain data of only one type. On the contrary, list
mobjects are special objects that can contain other objects.
You can access the mode of an object with the mode ()
function:
## [1] "numeric"
## [1] "character"
## [1] "list"
## [1] "logical"
## function (x)
## {
## if (is.expression(x))
## return("expression")
## if (is.call(x))
## return(switch(deparse(x[[1L]])[1L], `(` = "(", "call"))
## if (is.name(x))
## "name"
## else switch(tx <- typeof(x), double = , integer = "numeric",
## closure = , builtin = , special = "function", tx)
## }
## <bytecode: 0x7fa6e6dbaa90>
## <environment: namespace:base>
Besides the mode, an object also has a length, defined as the number of elements it contains:
## [1] 3
## [1] 3
## [1] 2
The class of an object specifies its behavior and therefore its way of interacting with operations and functions. An important example are data frames: special lists whose elements all have the same length. The class of a data frame is different from that of generic lists and data frames have an indexing system that does not exist for other lists:
## [1] "list"
## [1] "list"
## [1] "data.frame"
## [1] 33
A special object is the missing value NA
. By default, its mode is logical
, howeverNA
is neither TRUE
norFALSE
. To test if a value is missing we will use the is.na ()
function:
## [1] NA
## [1] TRUE
## [1] TRUE