1.6.1 If x <- c(“ww”, “ee”, “ff”, “uu”, “kk”), what will be the output for x[c(2,3)]?
x <- c("ww", "ee", "ff", "uu", "kk")
x[c(2,3)] # 2nd and 3rd
## [1] "ee" "ff"
1.6.2 If x <- c(“ss”, “aa”, “ff”, “kk”, “bb”), what will be the third value in the index vector operation x[c(2, 4, 4)]?
x <- c("ss", "aa", "ff", "kk", "bb")
x[c(2, 4, 4)] # 2nd, 4th & again 4th values which are "aa" "kk" "kk"
## [1] "aa" "kk" "kk"
1.6.3 If x <- c(“pp”, “aa”, “gg”, “kk”, “bb”), what will be the fourth value in the index vector operation x[-2]?
x <- c("pp", "aa", "gg", "kk", "bb")
x[-2] # all values except the 2nd one. So the 4th and the last value will be "bb"
## [1] "pp" "gg" "kk" "bb"
1.6.4 Let a <- c(2, 4, 6, 8) and b <- c(TRUE, FALSE, TRUE, FALSE), what will be the output for the R expression max(a[b])?
a <- c(2, 4, 6, 8)
b <- c(TRUE, FALSE, TRUE, FALSE)
a[b] # this expression will give us the values of a where their index in b is "TRUE". So this vector includes 2 and 6. Max expression gives the highest value.
## [1] 2 6
max(a[b])
## [1] 6
1.6.5 Let a <- c (3, 4, 7, 8) and b <- c(TRUE, TRUE, FALSE, FALSE), what will be the output for the R expression sum(a[b])?
a <- c (3, 4, 7, 8)
b <- c(TRUE, TRUE, FALSE, FALSE)
a[b] # 3,4
## [1] 3 4
sum(a[b]) # 3+4
## [1] 7
1.6.6 Write an R expression that will return the sum value of 10 for the vector x <- c(2, 1, 4, 2, 1, NA)
x <- c(2, 1, 4, 2, 1, NA)
#Sum of the all existing values is 10.
sum(x, na.rm = TRUE) # na.rm should be TRUE to ignore NA values. Otherwise, the sum would be NA.
## [1] 10
1.6.7 If x <- c(1, 3, 5, 7, NA) write an r expression that will return the output 1, 3, 5, 7.
x <- c(1, 3, 5, 7, NA)
x[!is.na(x)]
## [1] 1 3 5 7
1.6.8 Consider the data frame s <- data.frame(first= as.factor(c(“x”, “y”, “a”, “b”, “x”, “z”)), second=c(2, 4, 6, 8, 10, 12)). Write an R statement that will return the output 2, 4, 10, by using the variable first as an index vector.
# s is a data frame which has 2 columns and 6 rows. the rows with x or y values in their 1st column will give this output.
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
1.6.9 What will be the output for the R expression (c(FALSE, TRUE)) || (c(TRUE, TRUE))?
(c(FALSE, TRUE)) | (c(TRUE, TRUE)) ## wtf :D
## [1] TRUE TRUE
1.6.10 Write an R expression that will return the positions of 3 and 7 in the vector x <- c(1, 3, 6, 7, 3, 7, 8, 9, 3, 7, 2).
x <- c(1, 3, 6, 7, 3, 7, 8, 9, 3, 7, 2)
which(x %in% c(3, 7)) ## which expression gives the positions of the values.
## [1] 2 4 5 6 9 10