Agenda

Basic operators and data structures in R:

  • Operators
  • Basic data types and structures
  • Data frames.

Operators

Types:

  • Assignment operators: <-
  • Arithmetic operators: +-*/^
  • Relational operators: <>==
  • Logical operators: &|!

Assignment

Set variables x, y, z:

x <- 1
x
## [1] 1
y <- "Hello, R!"
z <- TRUE


Get variables list:

ls() # get vars list
## [1] "x" "y" "z"
rm(z) # remove z var
ls() # check result
## [1] "x" "y"

Arithmetic and math functions

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Exponentiation: ^
  • Division: /
  • Modulo: %%
  • Integer division: %/%.

_


Arithmetic operations:

(1 / 10 * (100 - 1000)) ^ 2
## [1] 8100

Math functions:

abs(log(cos(pi/exp(1))))
## [1] 0.908191

Relational and Logical operators

Example:

(1 >= 10) | ((3.14 == 3.14) & !FALSE)
## [1] TRUE

See also R Operators.

Data types

Data types:

  • scalars: numeric, character or logical values
  • vectors (one dimensional array): numeric, character or logical value; all elements have the same data type.
  • matrices (two dimensional array): numeric, character or logical values; all elements have the same data type.
  • lists: the different items on that list most likely differ in length, characteristic, and type of activity that has to be done.
  • data frames (two-dimensional objects): numeric, character or logical values; within a column all elements have the same data type, but different columns can be of different data type.

Data types (practice)

Vector and list:

c(x, 2, 3)
## [1] 1 2 3
list(a = y, b = c(x, 2, 3), с = NA)
## $a
## [1] "Hello, R!"
## 
## $b
## [1] 1 2 3
## 
## $с
## [1] NA

Matrix and array:

matrix(data = 1:15, nrow = 3, ncol = 5)
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    4    7   10   13
## [2,]    2    5    8   11   14
## [3,]    3    6    9   12   15
array(data = 1:24, dim = c(3, 4, 2))
## , , 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
## 
## , , 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24

Data frame:

data.frame(
  col1 = 1:10,
  col2 = seq(1, 20, by = 2),
  col3 = rep(Sys.time(), times = 10)
)
##    col1 col2                col3
## 1     1    1 2020-02-01 07:56:14
## 2     2    3 2020-02-01 07:56:14
## 3     3    5 2020-02-01 07:56:14
## 4     4    7 2020-02-01 07:56:14
## 5     5    9 2020-02-01 07:56:14
## 6     6   11 2020-02-01 07:56:14
## 7     7   13 2020-02-01 07:56:14
## 8     8   15 2020-02-01 07:56:14
## 9     9   17 2020-02-01 07:56:14
## 10   10   19 2020-02-01 07:56:14

Conclusion