2.1 Vectors - JulTob/R GitHub Wiki
In R, you create a vector with the combine function c(). You place the vector elements separated by a comma between the parentheses.
numeric_vector <- c(1, 2, 3)
character_vector <- c("a", "b", "c")
boolean_vector <- c(TRUE, FALSE, TRUE)
my_vector <- 1:10 # Vector with numerics from 1 up to 10
You can give a name to the elements of a vector with the names() function.
ID_vector <- c("John Doe", "Doctor")
names(ID_vector) <- c("Name", "Profession")profit_vector <- c(140, -50, 20, -120, 240)
days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
names(profit_vector) <- days_vectorAddition is element-wise.
a <- c(1, 2, 3)
b <- c(4, 5, 6)
# Take the sum
c <- a + b
# Print result
c
[1] 5 7 9a <- c(1, 2, 3)
sum(a)
[1] 6Per Element
a <- c(1, 2, 3)
a[1]
[1] 1proffit_vector <- c(140, -50, 20, -120, 240)
days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
names(proffit_vector) <- days_vector
# Define a new variable based on a selection
proffit_wednesday <- proffit_vector["Wednesday"]
proffit_wednesday
[1] 20Per Multi-Element
# Poker winnings from Monday to Friday:
poker_vector <- c(140, -50, 20, -120, 240)
days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
names(poker_vector) <- days_vector
# Define a new variable based on a selection
poker_midweek <- poker_vector[ c("Tuesday", "Wednesday", "Thursday")]
poker_midweekPer Range
signal <- c(140, -50, 20, -120, 240, 20, -30, 50, 120)
buffer <- signal[1:3]Comparing
-
<for less than -
>for greater than -
<=for less than or equal to -
>=for greater than or equal to -
==for equal to each other -
!=not equal to each other
c(4, 5, 6) > 5
[1] FALSE FALSE TRUEselect_positives <- signal > 0
pos_signal <- signal[select_positives]mean(signal)