[R] Deleting many list elements in one time

Duncan Murdoch murdoch at stats.uwo.ca
Mon Apr 5 17:24:11 CEST 2010


On 05/04/2010 11:17 AM, anna wrote:
> Hi guys, here is a simple thing I want to do but it doesn't work:
> I have a vector of the element indexes that I want to delete called index
> so when I write myList[[index]] <- NULL to delete these elements here is
> what I get:
> Error in myList[[index]] <- NULL : 
>   more elements supplied than there are to replace
> Isn't it possible to delete multiple elements?

If your index is a list of numerical indices as opposed to names, then 
just do

myList <- myList[-index]

the same way you'd delete elements from any vector.

If index is a vector of names, you need to convert it to numbers, using 
something like

indexnums <- which( names(myList) %in% index )

and then use myList[-indexnums].

Duncan Murdoch



More information about the R-help mailing list