Home > Net >  How to query the element of a vector which has a name that is an empty string?
How to query the element of a vector which has a name that is an empty string?

Time:07-23

Suppose I have an example where a vector has an element name that is empty:

vec <- c(3,2)
names(vec) <- c("","name1")
vec

I can call name1's element 2 by doing:

> vec["name1"]
name1 
    2

but I cannot get the empty name element 3. Is there a way to do this?

CodePudding user response:

A possible solution:

vec[names(vec) == ""]

#>   
#> 3

CodePudding user response:

It is documented in ?names

The name "" is special: it is used to indicate that there is no name associated with an element of a (atomic or generic) vector. Subscripting by "" will match nothing (not even elements which have no name).

Thus it is better to make use of make.names/make.unique to assign default value for the names that are ""

names(vec) <- make.names(names(vec))
> vec["X"]
X 
3 
  •  Tags:  
  • r
  • Related