250+ TOP MCQs on Subsetting and Answers

R Programming Questions and Answers for experienced focuses on “Subsetting”.

1. Which of the following extracts first element from the following R list?

 > x <- list(foo = 1:4, bar = 0.6)

a) x[[1]]
b) x[1]
c) x[[0]]
d) x[0]

Answer: a
Clarification: The [[ operator can also use named indices so that you don’t have to remember the exact ordering of every element of the list.

2. Point out the correct statement?
a) You can also use the $ operator to extract elements by name
b) $ operator can be used with computed indices
c) The [[ operator can only be used with literal names
d) $ operator semantics are similar to that of [[

Answer: a
Clarification: You don’t need the quotes when you use the $ operator.

3. What will be the output of the following R code?

> x <- list(foo = 1:4, bar = 0.6, baz = "hello")
> name <- "foo"
> x$name

a) 1
b) 2
c) 3
d) NULL

Answer: d
Clarification: Element “name” doesn’t exist.

4. What will be the output of the following R code?

> x <- list(foo = 1:4, bar = 0.6, baz = "hello")
> name <- "foo"
> x[[name]]

a) 1 2 3 4
b) 0 1 2 3
c) 1 2 3 4 5
d) All of the mentioned

Answer: a
Clarification: One thing that differentiates the [[ operator from the $ is that the [[ operator can be used with computed indices.

5. What will be the output of the following R code?

> x <- list(a = list(10, 12, 14), b = c(3.14, 2.81))
> x[[c(1, 3)]]

a) 13
b) 14
c) 15
d) 18

Answer: b
Clarification: The [[ operator can take an integer sequence if you want to extract a nested element of a list.

6. What will be the output of the following R code?

> x <- list(aardvark = 1:5)
> x$a

a) 1 2 3 4 5
b) 2 3 5
c) 1 3 3 5
d) 1 2 3

Answer: a
Clarification: Partial matching of names is allowed with [[ and $.

7. Which of the following code extracts 1st element of the 2nd element?

 > x <- list(a = list(10, 12, 14), b = c(3.14, 2.81))

a) x[[c(2, 1)]]
b) x[[c(1, 2)]]
c) x[[c(2, 1,1)]]
d) x[[(2, 2,1)]]

Answer: a
Clarification: [ operator always returns an object of the same class as the original.

8. What will be the output of the following R code?

> x <- list(aardvark = 1:5)
> x[["a", exact = FALSE]]

a) 1 2 3 4 5
b) 2 3 5
c) 1 3 3 5
d) 1 2 3

Answer: a
Clarification: This is often very useful during interactive work if the object you’re working with has very long element names.

9. What will be the output of the following R code?

> x <- c(1, 2, NA, 4, NA, 5)
> bad <- is.na(x)
> print(bad)

a) FALSE FALSE FALSE FALSE TRUE FALSE
b) FALSE TRUE TRUE FALSE TRUE FALSE
c) FALSE FALSE TRUE FALSE TRUE FALSE
d) FALSE TRUE TRUE TRUE TRUE FALSE

Answer: c
Clarification: A common task in data analysis is removing missing values (NAs).

Leave a Reply

Your email address will not be published. Required fields are marked *