-3

If I have a list of interger, and I gave them string names, how do i get the name based on the value?

Is that possible?

Thanks

Joyce
  • 1,431
  • 2
  • 18
  • 33
  • 1
    A [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) would make your question more precise and easier to verify potential answers. – MrFlick May 08 '15 at 15:56

2 Answers2

4
x <- list(a=2L,b=3L) 
names(x[which(x==2)])
Frank
  • 66,179
  • 8
  • 96
  • 180
Shenglin Chen
  • 4,504
  • 11
  • 11
1

match with names works:

x <- list(a=2L,b=3L)

names(x)[match(2L,x)]
# [1] "a"

This also works if x is not actually a list, but a vector: x <- c(a=2L,b=3L).

If the value is not unique, it selects the first match:

x <- list(a=2L,b=3L,d=2L)
names(x)[match(2L,x)] # still "a"
Frank
  • 66,179
  • 8
  • 96
  • 180