⸻ Exercise 1: Sequence Generation Question: Generate a sequence from 10 to -10 decreasing by 2. What is the output?
Answer:
seq(10, -10, by = -2)
## [1] 10 8 6 4 2 0 -2 -4 -6 -8 -10
Exercise 2: Difference Between seq() and seq_along() Question: Given x <- c(4, 5, 6), compare seq(x) and seq_along(x).
Answer:
x <- c(4, 5, 6)
seq(x)
## [1] 1 2 3
seq_along(x)
## [1] 1 2 3
Exercise 3: Repeating Elements Question: Repeat the vector c(“A”, “B”, “C”) with each element repeated 2, 3, and 1 times respectively.
Answer:
rep(c("A", "B", "C"), times = c(2, 3, 1))
## [1] "A" "A" "B" "B" "B" "C"
Exercise 4: Sorting and Ordering Question: Sort the vector v <- c(3, 5, 9, 7, 14, 2) and show the order of indices.
Answer:
v <- c(3, 5, 9, 7, 14, 2)
sort(v)
## [1] 2 3 5 7 9 14
order(v)
## [1] 6 1 2 4 3 5
Exercise 5: Logical Subsetting Question: Given state <- c(“FL”, “GA”, “FL”, “AL”), extract elements where state is “FL”.
Answer:
state <- c("FL","GA","FL","AL")
state[state == "FL"]
## [1] "FL" "FL"
Exercise 6: Handling Missing Data Question: Replace all NA values in x <- c(1, NA, 3, NA, 5) with 0.
Answer:
x <- c(1, NA, 3, NA, 5)
x[is.na(x)] <- 0
x
## [1] 1 0 3 0 5
Exercise 7: Creating New Variables Question: Create a new column total in a data frame with x1 and x2 as columns.
Answer:
df <- data.frame(x1 = c(1, 2), x2 = c(3, 4))
df$total <- df$x1 + df$x2
df
Exercise 8: Recoding Values Question: Recode all values equal to 99 in v <- c(1, 99, 3, 99) to NA.
Answer:
v <- c(1, 99, 3, 99)
v[v == 99] <- NA
v
## [1] 1 NA 3 NA
Exercise 9: Subsetting with %in% Question: Extract elements from vec1 <- c(10, 20, 30) that are also in vec2 <- c(20, 40).
Answer:
vec1 <- c(10,20,30)
vec2 <- c(20,40)
vec1[vec1 %in% vec2]
## [1] 20
Exercise 10: Subsetting Data Frame Question: From the data frame df <- data.frame(name = c(“Alice”, “Bob”), age = c(25, 35)), extract rows where age > 30. 1) using matrix 2) using subset()
Answer 1):
#using matrix
df <- data.frame(name=c("Alice","Bob"), age=c(25,35))
df[df$age > 30, ]
Answer 2):
#using subset()
df <- data.frame(name=c("Alice","Bob"), age=c(25,35))
subset(df, age > 30)