21

I know that with a vector such as

v <- c("MA", "NY", "PA")
names(v) <- c("Massachusetts", "New York", "Pennsylvania")

It is possible to get a value from a name using syntax such as

v["New York"]

But is it possible to get a name from a value (like the PHP key() function)? Thanks.

2 Answers 2

28

Lots of ways to do this.

names(v)[v == "NY"] # extract the names, subset by equality to NY
# or
names(which(v == "NY")) # extract entries that == NY and get names

to name a few.

2
  • names(v)[v == "NY"] looks like the easiest syntax, thank you. Still wish there were a basic function like key() though. Will have to write my own to use in my own code.
    – Sharon
    Commented Jan 29, 2014 at 4:52
  • 1
    Just be careful about NAs when using this syntax: v <- c("MA", "NY", "PA",NA); names(v) <- c("Massachusetts", "New York", "Pennsylvania","Guam"); names(v)[v=="NY"]; #[1] "New York" NA Commented Jan 29, 2014 at 5:19
8

Use match

names(v)[match("NY",v)]

or use which

names(v)[which(v=="NY")]
1
  • I prefer the match() approach - it's cleaner. My vote goes here. thumbs-up to you man !!!
    – SilSur
    Commented Aug 2, 2022 at 7:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.