Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get name from a value in an R vector with names

Tags:

r

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.

like image 624
Sharon Avatar asked Jan 29 '14 04:01

Sharon


2 Answers

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.

like image 198
mathematical.coffee Avatar answered Sep 28 '22 15:09

mathematical.coffee


Use match

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

or use which

names(v)[which(v=="NY")]
like image 40
Jeremy Coyle Avatar answered Sep 28 '22 16:09

Jeremy Coyle