I'm implementing an algorithm that involves lots of adding and removing things from sets. In R, this is slow because as far as I know, adding or removing things from a vector is slow, since the entire vector has to be re-allocated. Is there a way do do it more efficiently?
Edit: My current solution is to use a boolean vector of the same length as the list of things that can be in the set, and using that as a membership table.
To append multiple elements to a Vector in R, use the append() method and pass the vector to the existing vector. It will spread out in the existing vector and add multiple elements to that vector.
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.
Adding elements in a vector in R programming – append() method. append() method in R programming is used to append the different types of integer values into a vector in the last. Return: Returns the new vector after appending given value.
To append an element in the R List, use the append() function. You can use the concatenate approach to add components to a list. While concatenate does a great job of adding elements to the R list, the append() function operates faster.
Chapter 2 of The R Inferno has some interesting comments on this, including perdiodic growing objects to reduce memory fragmentation and allocation overhead.
If you know what the ultimate size of the set is, then the method you suggest is probably the best - ie subset
from the whole universe using an approprate membership vector. Difficult to know whats best without seeing exactly what you are trying to do though.
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