从R中的"值"获得"密钥"

use*_*769 4 indexing r key list

我创建了一个列表,其中包含多个列表.我试图确定从"价值"获得"关键"的有效方法.即如果我指定("猫"或"狗"),("鱼"或"鸡"),("马"或"驴")我怎样才能分别返回"宠物","食物"和"工作" .我试图创建一个带有for循环的方法,因为我不确定如何通过名称进行索引处理.

pet <- c("cat", "dog")
food <- c("fish", "chicken")
work <- c("horse", "donkey")

types <- c("pet", "food", "work")

animal.list <- vector(mode = "list", length = length(types))
names(animal.list) <- types

for (i in types)
{
  animal.list[[i]] <-  vector(mode = "list", length = length(c("a", "b")))
  names(animal.list[[i]]) <- c("a", "b")
  animal.list[[i]][["a"]] <- eval(parse(text = i))[[1]]
  animal.list[[i]][["b"]] <- eval(parse(text = i))[[2]]

}
Run Code Online (Sandbox Code Playgroud)

我的尝试看起来像这样,但希望我可以使用某种(%in%)语句来更有效/更紧凑地执行它.

f <- function(x)
{
    ret <- NULL
    for (i in animals)
    {

         if(x == animal.list[[i]][["a"]] | x == animal.list[[i]][["b"]])
         {
             ret <- i
         }
     }

}
Run Code Online (Sandbox Code Playgroud)

Bro*_*ieG 7

您可以使用,创建查找表stack,然后使用它match来查找值:

animals <- stack(list(pet=pet, food=food, work=work))
f <- function(x) as.character(animals[match(x, animals[[1]]), 2])
Run Code Online (Sandbox Code Playgroud)

然后:

f("cat")
# [1] "pet"
f("horse")
# [1] "work"
Run Code Online (Sandbox Code Playgroud)

注意%in%只是一个变种match.

您还可以使用R的内置字符查找:

animal.vec <- as.character(animals[[2]])
names(animal.vec) <- animals[[1]]
animal.vec[c("cat", "horse")]
#   cat  horse 
# "pet" "work
Run Code Online (Sandbox Code Playgroud)