For time series analysis I handle data that often contains leading and trailing zero elements. In this example, there are 3 zeros at the beginning an 2 at the end. I want to get rid of these elements, and filter for the contents in the middle (that also may contain zeros)
vec <- c(0, 0, 0, 1, 2, 0, 3, 4, 0, 0)
I did this by looping from the beginning and end, and masking out the unwanted elements.
mask <- rep(TRUE, length(vec))
# from begin
i <- 1
while(vec[i] == 0 && i <= length(vec)) {
mask[i] <- FALSE
i <- i+1
}
# from end
i <- length(vec)
while(i >= 1 && vec[i] == 0) {
mask[i] <- FALSE
i <- i-1
}
cleanvec <- vec[mask]
cleanvec
[1] 1 2 0 3 4
This works, but I wonder if there is a more efficient way to do this, avoiding the loops.
To delete an item at specific index from R Vector, pass the negated index as a vector in square brackets after the vector. We can also delete multiple items from a vector, based on index.
To remove the last elements of a vector, we can use head function with negative sign of the number of values we do not want. For example, if we have a vector of length 200 but we don't want last fifty elements then we can use head(vector_name,-50).
You can use the following basic syntax to remove specific elements from a vector in R: #remove 'a', 'b', 'c' from my_vector my_vector[! my_vector %in% c('a', 'b, 'c')] The following examples show how to use this syntax in practice. Example 1: Remove Elements from Character Vector
R Vector. It contains element of the same type. The data types can be logical, integer, double, character, complex or raw. A vector’s type can be checked with the typeof () function. Another important property of a vector is its length. This is the number of elements in the vector and can be checked with the function length ().
First, we have to create an example vector: Now, we can subset our vector by specifying the index positions we want to remove with a minus sign in front: As you can see based on the previous output of the RStudio console, we kept only the last three elements.
The previous output of the RStudio console shows that our example data is a vector object with ten elements. The items of our example vector reflect an alphabetical range from “a” to “j”. Example 1 illustrates how to remove only the very last element from our vector.
vec[ min(which(vec != 0)) : max(which(vec != 0)) ]
Basically the which(vec != 0)
part gives the positions of the numbers that are different from 0, and then you take the min and max of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With