Basics of R (Review)

Assignment

[1]:
a <- 2
b <- 3
[2]:
a + b
5

Custom function

[3]:
add <- function(a, b) {
    a + b
}
[4]:
add(a, b)
5

Vectors

[5]:
seq(1, 5)
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
[6]:
1:5
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
[7]:
c(1,2,3,4,5)
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5

Named vectors

[8]:
c(a=1, b=2, c=3, d=4, e=5)
a
1
b
2
c
3
d
4
e
5

Lists

[9]:
list(a=1, b=TRUE, c="hello")
$a
1
$b
TRUE
$c
'hello'

Data Frames

A Data Frame is a special kind of List where all elements are vectros fo the same length.

[10]:
data.frame(a=1:5, b=6:10, c=rnorm(5))
A data.frame: 5 × 3
abc
<int><int><dbl>
1 6-0.2701866
2 7 0.4624501
3 8 0.1019228
4 9-1.5094554
510 0.4304919

Basic Data Frame manipulation

[11]:
df <- data.frame(a=1:5, b=6:10, c=rnorm(5))
[12]:
df
A data.frame: 5 × 3
abc
<int><int><dbl>
1 6 0.5207780
2 7-1.5697044
3 8 0.3914048
4 9-0.5415737
510-0.9471250

Get columns

[13]:
df$b
  1. 6
  2. 7
  3. 8
  4. 9
  5. 10
[14]:
df[['b']]
  1. 6
  2. 7
  3. 8
  4. 9
  5. 10
[15]:
df[,2]
  1. 6
  2. 7
  3. 8
  4. 9
  5. 10

Get rows

[16]:
df[3,]
A data.frame: 1 × 3
abc
<int><int><dbl>
3380.3914048
[17]:
df[c(1,3), ]
A data.frame: 2 × 3
abc
<int><int><dbl>
1160.5207780
3380.3914048

Get cell

[18]:
df[2,3]
-1.56970441859343

Get sub-frame

[19]:
df[c(1,3)]
A data.frame: 5 × 2
ac
<int><dbl>
1 0.5207780
2-1.5697044
3 0.3914048
4-0.5415737
5-0.9471250
[20]:
df[c(1,3), 2:3]
A data.frame: 2 × 2
bc
<int><dbl>
160.5207780
380.3914048
[ ]: