Skip to content
Prev 321670 / 398500 Next

Removing multiple elements from a vector or list

On Apr 15, 2013, at 2:30 PM, arun wrote:

            
alp <- as.list(letters) would have constructed the vector that was described.
All good. There would be an additional way to do this if the list were first assigned names. (At the moment the list only has positions for reference.)

alp <- setNames(alp, letters[1:26])
# Something like that initial code would succeed:

alp <- alp[ !names(alp) %in% c("b","r","x")]

The result is still a list.
You _cannot_use_negative_indexing_with_names (or values). You could have used logical indexing:

alp [ sapply(alp, function(x) !x %in% c("b","r","x") ) ]

# OR perhaps the most compact solution offered so far;  numeric indexing with the minus unary operator:

alp[ -grep("b|r|x", alp) ]