R Vectors

Vectors in R are one-dimensional arrays that can hold numeric data, character data, or logical data. They are the most basic data structures in R and are used extensively for data analysis.

Key Topics

Vector Creation

You can create vectors using the c() function, which combines values into a vector.

# Creating vectors
numeric_vector <- c(1, 2, 3, 4, 5)
character_vector <- c("apple", "banana", "cherry")
logical_vector <- c(TRUE, FALSE, TRUE)

print(numeric_vector)
print(character_vector)
print(logical_vector)

Output:

[1] 1 2 3 4 5
[1] "apple" "banana" "cherry"
[1] TRUE FALSE TRUE

Code Explanation: The c() function is used to create vectors. The vectors numeric_vector, character_vector, and logical_vector contain numeric, character, and logical values, respectively.

Vector Operations

You can perform arithmetic operations on numeric vectors and use functions to manipulate vector elements.

# Vector arithmetic
v1 <- c(1, 2, 3)
v2 <- c(4, 5, 6)
sum_vector <- v1 + v2

# Accessing vector elements
element <- v1[2]

print(sum_vector)
print(element)

Output:

[1] 5 7 9
[1] 2

Code Explanation: Vectors v1 and v2 are added element-wise to produce sum_vector. The second element of v1 is accessed using square brackets.

Key Takeaways

  • Vectors are created using the c() function and can hold elements of the same data type.
  • Arithmetic operations on numeric vectors are performed element-wise.
  • You can access vector elements using square brackets.