Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently adding or removing elements to a vector or list in R?

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.

like image 744
Ryan C. Thompson Avatar asked May 06 '10 04:05

Ryan C. Thompson


People also ask

How do I add multiple elements to a vector in R?

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.

How do I remove an element from a vector in R?

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.

How do I add elements to a vector in R?

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.

How do I add an element to a list in R?

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.


1 Answers

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.

like image 72
James Avatar answered Oct 21 '22 21:10

James