Search notes:
R operators
Brackets for subscript (subsetting)
How the indices in a subscript are interpreted is dependent on its type and value:
Subscript | Selected items |
Positive numbers | Items that correspond to numbers |
Negative numbers | Inversion of positive numbers |
Character vector | Named items (dimnames) |
Logical vector | Corresponding TRUE items - NA where NA |
If missing | All items |
v <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
v[4]
# [1] 4
v[3:6]
# [1] 3 4 5 6
v[6:3]
# [1] 6 5 4 3
v[-2]
# [1] 1 3 4 5 6 7 8 9 10
#
# Note the 2nd element!
#
# --- subscripting with boolean vectors:
cities <- c("New York", "Paris", "Tokyo", "Amsterdam", "Johannesburg", "Berlin", "Berne", "Frankfurt")
cityname.shorter.8 <- nchar(cities) < 8
cityname.shorter.8
# [1] FALSE TRUE TRUE FALSE FALSE TRUE TRUE FALSE
cities[cityname.shorter.8]
# [1] "Paris" "Tokyo" "Berlin" "Berne"
Colon
#
# Compare with -> seq()
#
10:15
# [1] 10 11 12 13 14 15
# This is exactly the same as
seq(10,15)
Assignment
x <- c(1, 2, 3, 4)
Assignment (<<-)
g1 <- 1
g2 <- 2
f <- function(a, b, c, d, call_f) {
if (call_f) f(100, 200, 300, 400, FALSE)
g1 <- a
g2 <<- b
g3 <- c
g4 <<- d
}
f(10, 20, 30, 40, TRUE)
g1
# [1] 1
g2
# [1] 20
# g3 # Error: object 'g3' not found
g4
# [1] 40
Addition
print ( 4 + 5 )
# [1] 9
v <- c ( 2, 3, 4 )
print ( v + 1 )
# [1] 3 4 5
w <- c ( 7, 1, 5 )
print ( v + w )
# [1] 9 4 9
Substraction
print ( 20 - 9 )
# [1] 11
v <- c (5, 7, 10)
print ( v - 2 )
# [1] 3 5 8
w <- c (1, 2, 3)
print ( v - w )
# [1] 4 5 7
Multiplication
p6 <- c(2, 3, 5, 7, 11, 13)
v <- c(1, 2, 3, 4, 5, 6)
#
#
#
p6 * v
# [1] 2 6 15 28 55 78
# --------------
w <- 1:4
p6*w
# [1] 2 6 15 28 11 26
# Warning message:
# In p6 * w : longer object length is not a multiple of shorter object length
%…%
#
# % … % allows to create user defined binary operators
#
# Some are already defined, for example
# %/% : integer division
# %*% : Matrix mulitplication
#
# Defining my own binary operator. Note the apostrophes:
'%foo%' <- function (x, y) {
(x-y)*min(x,y)
}
7 %foo% 5
# [1] 10
7 %foo% 3
# [1] 12
Modulus
print ( 117 %% 10 )
# [1] 7
Integer division
print ( 103 / 25 )
# [1] 4.12
print ( 103 %/% 25 )
# [1] 4