Let's say I had a vector:
remove <- c(17, 18, 19, 20, 24, 25, 30, 31, 44, 45)
.
How do I select / extract every second value in the vector? Like so: 17, 19, 24, 30, 44
I'm trying to use the seq
function: seq(remove, 2)
but it doesn't quite work.
Any help is greatly appreciated.
The seq() method in R, is used to generate sequences, out of the objects they refer to. The seq() method, extracts a subset of the original vector, based on the constraints, that is the start and end index, as well as the number of steps to increment during each iteration.
Vectors are basic objects in R and they can be subsetted using the [ operator. The [ operator can be used to extract multiple elements of a vector by passing the operator an integer sequence.
To find the position of odd numbers in an R vector, we can find the position of values that are divisible by 2 with the help of which function. For example, if we have a vector called x then we can find the position of odd numbers using the command which(x%%2==1).
remove[c(TRUE, FALSE)]
will do the trick.
How it works?
If logical vectors are used for indexing in R, their values are recycled if the index vector is shorter than the vector containing the values.
Here, the vector remove
contains ten values. If the index vector c(TRUE, FALSE)
is used, the actual command is: remove[c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE)]
Hence, all values with odd index numbers are selected.
remove[seq(1,length(remove),2)]
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