【发布时间】: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
}
}
}
【问题讨论】: