【问题标题】:Obtain "key" from "value" in R从R中的“值”中获取“键”
【发布时间】:2015-03-19 08:28:36
【问题描述】:

我创建了一个列表,它本身由几个列表组成。我正在尝试确定一种从“值”中获取“键”的有效方法。 IE。如果我指定(“猫”或“狗”)、(“鱼”或“鸡”)、(“马”或“驴”),我如何分别返回“宠物”、“食物”和“工作”。我试图创建一个带有 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]]

}

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

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

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

}

【问题讨论】:

    标签: r list indexing key


    【解决方案1】:

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

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

    然后:

    f("cat")
    # [1] "pet"
    f("horse")
    # [1] "work"
    

    注意%in% 只是match 的变体。

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

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

    【讨论】:

    • @AriB.Friedman 这一切都归功于 Ananda Mahto,他教了我这个,还有很多其他的。
    【解决方案2】:

    您可以使用单括号而不是双括号来选择列表的多个元素。结合any%in%

    #  ("cat" or "dog")
    idx <- sapply( animal.list, function(x) any( x %in% c("cat", "dog")) )
    names( animal.list )[ idx ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-30
      相关资源
      最近更新 更多