Index vectors

December 21, 2015
By

(This article was first published on R-exercises, and kindly contributed to R-bloggers)

In the exercises below we cover the basics of index vectors. Before proceeding, first read section 2.7 of An Introduction to R, and the help pages for the sum, and which functions.

Answers to the exercises are available here.

Exercise 1
If x <- c("ww", "ee", "ff", "uu", "kk"), what will be the output for x[(c(2,3)]?
a. "ee", "ff"
b. "ee"
c. "ff"

Exercise 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)]?
a. "uu"
b. NA
c. "kk"

Exercise 3
If x <- c("pp", "aa", "gg", "kk", "bb"), what will be the fourth value in the index vector operation x[-2]?
a. "aa"
b. "gg"
c. "bb"

Exercise 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])?

Exercise 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])?

Exercise 6
Write an R expression that will return the sum value of 10 for the vector x <- c(2, 1, 4, 2, 1, NA)

Exercise 7
If x <- c(1, 3, 5, 7, NA) write an r expression that will return the output 1, 3, 5, 7.

Exercise 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.

Exercise 9
What will be the output for the R expression (c(FALSE, TRUE)) || (c(TRUE, TRUE))?

Exercise 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).

To leave a comment for the author, please follow the link and comment on their blog: R-exercises.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)