0
0
R Programmingprogramming~5 mins

Negative indexing for exclusion in R Programming - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does negative indexing do in R when used with vectors?
Negative indexing in R excludes elements at the specified positions from a vector. For example, x[-2] returns all elements except the second one.
Click to reveal answer
beginner
How do you exclude multiple elements from a vector using negative indexing?
You provide a vector of negative indices. For example, x[-c(1,3)] excludes the first and third elements from x.
Click to reveal answer
intermediate
What happens if you mix positive and negative indices in R when subsetting a vector?
R will give an error because you cannot mix positive and negative indices in the same subset operation.
Click to reveal answer
beginner
Example: Given x <- c(10, 20, 30, 40), what is the result of x[-2]?
The result is c(10, 30, 40) because the second element (20) is excluded.
Click to reveal answer
beginner
Why is negative indexing useful in data manipulation?
It allows you to quickly remove unwanted elements without creating a new vector or using complex functions.
Click to reveal answer
What does x[-1] do in R if x is a vector?
ACauses an error
BReturns only the first element
CReturns the vector unchanged
DReturns all elements except the first one
Which of these is a valid way to exclude the 2nd and 4th elements from a vector x?
Ax[-c(2,4)]
Bx[c(-2,-4)]
Cx[c(2,4)]
Dx[-2,4]
What happens if you try x[c(1, -2)] in R?
AReturns elements 1 and excludes 2
BGives an error
CReturns all elements
DReturns elements 1 and 2
If x <- c(5, 10, 15, 20), what is x[-3]?
Ac(5, 10, 20)
Bc(5, 10, 15)
Cc(15, 20)
Dc(10, 15, 20)
Why might you use negative indexing instead of positive indexing?
ATo reverse the vector
BTo select only the first element
CTo exclude unwanted elements easily
DTo sort the vector
Explain how negative indexing works in R and give an example.
Think about removing elements by position.
You got /3 concepts.
    What error occurs if you mix positive and negative indices in R? Why?
    Consider how R expects indexing to be consistent.
    You got /3 concepts.