Introduction
Negative indexing helps you remove items from a list or vector easily without changing the original order.
vector[-index] vector[-c(index1, index2, ...)]
x <- c(10, 20, 30, 40, 50) x[-2]
x <- c(10, 20, 30, 40, 50) x[-c(1, 5)]
x <- c('a', 'b', 'c', 'd') x[-3]
numbers <- c(5, 10, 15, 20, 25) # Remove the 3rd element result <- numbers[-3] print(result)
x[-2] do to the vector x?x[-2]x, returning all others.x without the second element. -> Option Cv in R?c(), like -c(1, 3).v[-c(1, 3)] to exclude 1st and 3rd elements. Others misuse negative signs or commas.vec <- c(10, 20, 30, 40, 50) result <- vec[-c(2, 4)] print(result)
-c(2, 4) removes elements at positions 2 and 4, which are 20 and 40.nums <- c(5, 10, 15, 20) new_nums <- nums[-2, 3] print(new_nums)
nums[-2, 3] implies matrix indexing, which is invalid for a vector.nums is a vector, not a matrix or data frame.data <- c(3, 6, 9, 12, 15, 18). You want to create a new vector excluding all elements at even positions using negative indexing. Which code correctly achieves this?seq(2, length(data), by=2) generates these positions dynamically.-seq(2, length(data), by=2) removes elements at even positions.Pass the test and this pattern moves unknown