SkyWalker
SkyWalker

Reputation: 14309

How to remove an element by name from a named vector?

How to remove an element from a named vector by name? e.g.

v <- c(1, 2, 3)
names(v) <- c('a', 'b', 'c') 
# how to remove b?
v['b'] <- NULL # doesn't work
Error in v["b"] <- NULL : replacement has length zero

Upvotes: 7

Views: 3793

Answers (2)

akrun
akrun

Reputation: 887048

Or we can use an index with match

v[-match("b", names(v))]

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 388907

You could use

v[names(v) != "b"]
#a c 
#1 3 

Or with setdiff

v[setdiff(names(v), "b")]

Upvotes: 5

Related Questions