Data Stucture: Vector

Create a vector named numbers with the values 2, 4, 6, 8, and 10. Print the vector to confirm its contents.

Solution:

numbers <- c(2, 4, 6, 8, 10)
numbers

Use the numbers vector. Add 5 to each element and print the resulting vector. Then, multiply each element by 3.

Solution:

# Adding 5 to each element
numbers + 5

# Multiplying each element by 3
numbers * 3

Given the vector months <- c("Jan", "Feb", "Mar", "Apr", "May"), retrieve the third element. Try accessing multiple elements by extracting the first, third, and fifth elements.

Solution:

months <- c("Jan", "Feb", "Mar", "Apr", "May")

# Accessing the third element
months[3]

# Accessing the first, third, and fifth elements
months[c(1, 3, 5)]

Create a vector of odd numbers from 1 to 15. Use the length() function to find out how many elements are in the vector.

Solution:

odd_numbers <- seq(1, 15, by = 2)
length(odd_numbers)

Given scores <- c(65, 85, 78, 90, 58, 92), create a vector of only the scores that are above 80 using logical indexing.

Solution:

scores <- c(65, 85, 78, 90, 58, 92)
high_scores <- scores[scores > 80]
high_scores

Create two vectors, x <- c(1, 2, 3) and y <- c(4, 5, 6). Combine them into a single vector named z and print the result.

Solution:

x <- c(1, 2, 3)
y <- c(4, 5, 6)
z <- c(x, y)
z

Given a vector of random numbers, random_numbers <- c(5, 12, 3, 8, 7), sort it in ascending order and then in descending order.

Solution:

random_numbers <- c(5, 12, 3, 8, 7)

# Sorting in ascending order
sort(random_numbers)

# Sorting in descending order
sort(random_numbers, decreasing = TRUE)

Create a vector data <- c(3, 7, 9, 2, 8). Find the sum, mean, and standard deviation of the elements in the vector.

Solution:

data <- c(3, 7, 9, 2, 8)

# Sum of elements
sum(data)

# Mean of elements
mean(data)

# Standard deviation of elements
sd(data)

Given the vector numbers <- c(10, 20, 30, 40, 50), remove the element with value 30. Print the updated vector.

Solution:

numbers <- c(10, 20, 30, 40, 50)
numbers <- numbers[numbers != 30]
numbers

Use the vector x <- c(2, 4, 6) and another vector y <- c(1, 2). Add x and y together to see how R handles vector recycling. Explain the result.

Solution:

x <- c(2, 4, 6)
y <- c(1, 2)

result <- x + y
result


# Explanation: R "recycles" y to match the length of x. So the calculation is:
# 2 + 1 = 3
# 4 + 2 = 6
# 6 + 1 = 7