To slice a vector in R, you can use the indexing notation with square brackets [ ].
In this example,
vec
containing some elements.vec[start:end]
to slice the vector from index start
to index end
.# Slice a vector by index range
vec <- c(1, 2, 3, 4, 5)
start <- 2
end <- 4
sliced_vec <- vec[start:end]
print(sliced_vec)
[1] 2 3 4
In this example,
vec
containing some elements.# Slice a vector by logical condition
vec <- c(1, 2, 3, 4, 5)
condition <- vec > 2
sliced_vec <- vec[condition]
print(sliced_vec)
[1] 3 4 5
In this tutorial, we learned How to Slice a Vector in R language with well detailed examples.