如何根据其值获取变量的名称

时间:2021-03-02 23:49:15

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

如果我有一个interger列表,并且我给了它们字符串名称,我如何根据值得到名称?

Is that possible?

那可能吗?

Thanks

2 个解决方案

#1


x <- list(a=2L,b=3L) 
names(x[which(x==2)])

#2


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).

如果x实际上不是列表,而是向量: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"

#1


x <- list(a=2L,b=3L) 
names(x[which(x==2)])

#2


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).

如果x实际上不是列表,而是向量: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"