2. Working with Vectors Flashcards
Indexing vectors by position
Extract a single element:
vector[1]
Extract a range of elements:
vector[3:7]
Extract multiple elements:
vector[c(2,5,7)]
Displaying data types
Display the data type of a vector:
typeof(vector)
Naming vector elements
Assign name attributes to a vector:
names(vector) <- name_vector
Indexing vectors by name
Extract a single element:
vector[“name_2”]
Extract multiple elements:
vector[c(“name_1”, “name_2)]
Logical operators
Less than: vector_1 < vector_2
Greater than: vector_1 > vector_2
Less than or equal to: vector_1 <= vector_2
Greater than or equal to: vector_1 >= vector_2
Equal to: vector_1 == vector_2
Not equal to: vector_1 != vector_2
Logical indexing
Indexing into a numeric vector using a logical vector: numeric_vector[logical_vector]
Performing arithmetic on vectors
Add, divide, or multiply vectors:
vector_1 + vector_2
vector_1 / vector_2
vector_1 * vector_2
Concepts
R recognizes different data types:
- Numeric (3, 5.66, 199, 6)
- Character (“math”, “%”, “&”, “chem+math”)
- Logical (TRUE, FALSE)
R is a 1-indexed programming language, which means that the first element in a vector is assigned a position of one.
When performing operations on vectors of unequal length, R “recycles” values of the shorter vector until the two vectors are the same length.