yliueagle
yliueagle

Reputation: 1201

Named values: what if 2 values have same name

For a vector of named values vec = 1:3, names(vec) = c('x1','x2','x1'), how R deals with different values with the same name? For example vec['x1'] only returns the first value named 'x1'. What if I want to access other values with the same name? Though it's not a good idea to have different objects sharing the same name.

Upvotes: 1

Views: 72

Answers (2)

Carl Witthoft
Carl Witthoft

Reputation: 21502

To add to Ananda's suggestion, I would fix your naming ASAP:

names(vec)<-make.names(names(vec),unique=TRUE)

#  x1   x2 x1.1 

Upvotes: 1

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193527

You can use %in% for cases when there would be multiple matches, but yes, it's not a good idea to have different objects sharing the same name.

> vec[names(vec) %in% "x1"]
x1 x1 
 1  3

Upvotes: 1

Related Questions