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

前端 未结 4 785
予麋鹿
予麋鹿 2020-12-31 06:22

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 vect

4条回答
  •  Happy的楠姐
    2020-12-31 06:57

    It's hard to say what you want. Maybe you really want stack commands like push and pop. The following isn't that. But it's a fast solution.

    Allocate a vector large enough to hold all of your items of the type you need. Set every value to NA. Adding items is simple. Removing items is setting them to NA again. Using the vector is just na.omit(myVec)

    myVec <- numeric (maxLength)  # a vector of maximum length
    
    is.na(myVec) <- 1:maxLength   # set every item in myVec to NA
    
    myVec[c(2,6,20)] <- 5         # add some values
    
    na.omit(myVec)
    
    #This will also work if you can initialize all of your values to something that you know you won't need. 
    

提交回复
热议问题