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)`

.

**What's next:**

- Become a Top R Programmer Fast with our Individual Coaching Program
- Explore all our (>4000) R exercises
- Find an R course using our R Course Finder directory
- Subscribe to receive weekly updates and bonus sets by email
- Share with your friends and colleagues using the buttons below

hassan says

is number supposed to be x[c(2,3)]?

Onno Dijt says

Hi Hassan,

Yes that is the correct code, thank you for spotting this!

Kind regards,

Onno

Sergio says

Solutions to 8 return 2,4,8,10, not 2,4,10.

Kung Fury says

Could you please share your solution?

s$second[(s$first==’x’) | (s$first==’y’)] should give the values on second column where we have x or y on the first column. the result is 2,4,10 for me

Daniel D says

A different solution would be:

s[s$first=c(‘x’, ‘y’),2]