简体   繁体   中英

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

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.

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.

Use match

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

or use which

names(v)[which(v=="NY")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM