[emaillocker]Below are the solutions to these exercises on index vectors.
# Exercise 1 x <- c("ww", "ee", "ff", "uu", "kk") x[c(2, 3)]
## [1] "ee" "ff"
#(Answer: a) # Exercise 2 x <- c("ss", "aa", "ff", "kk", "bb") y <- x[c(2, 4, 4)] y[3]
## [1] "kk"
# (Answer: c) # Exercise 3 x <- c("pp", "aa", "gg", "kk", "bb") y <- x[-2] y[4]
## [1] "bb"
# (Answer: c) # Exercise 4 a <- c(2, 4, 6, 8) b <- c(TRUE, FALSE, TRUE, FALSE) max(a[b])
## [1] 6
#(Answer: 6) # Exercise 5 a <- c(3, 4, 7, 8) b <- c(TRUE, TRUE, FALSE, FALSE) sum(a[b])
## [1] 7
#(Answer: 7) # Exercise 6 x <- c(2, 1, 4, 2, 1, NA) sum(x, na.rm=TRUE)
## [1] 10
sum(x[-6]) # alternative solution
## [1] 10
# Exercise 7 x <- c(1, 3, 5, 7, NA) x[!is.na(x)]
## [1] 1 3 5 7
x[-5] # alternative solution
## [1] 1 3 5 7
# Exercise 8 s <- data.frame(first= as.factor(c("x", "y", "a", "b", "x", "z")), second=c(2, 4, 6, 8, 10, 12)) s$second[(s$first=='x') | (s$first=='y')]
## [1] 2 4 10
s$second[s$first %in% c('x', 'y')] # alternative solution
## [1] 2 4 10
# Exercise 9 (c(FALSE, TRUE)) || (c(TRUE, TRUE))
## [1] TRUE
# Exercise 10 x <- c(1, 3, 6, 7, 3, 7, 8, 9, 3, 7, 2) which(x %in% c(3, 7))
## [1] 2 4 5 6 9 10
[/emaillocker]
One solution to problem 10 is:
x[c(3,7)]