将`which`与长度大于1的列表组件一起使用

时间:2015-11-22 13:07:11

标签: r list which

我有一个类似于以下内容的列表:

> x <- list(
    j = "first",
    k = "second",
    l = "third",
    m = c("first", "second"),
    n = c("first", "second", "third"),
    o = c("first", "third"),
    p = c("second", "third"),
    q = "first",
    r = "third")

我需要根据字符串组件的值创建字符串组件的索引。对于包含单个字符串元素的组件,我可以使用which轻松完成此操作:

> which(x == "third")
l r
3 9

甚至包含单个字符串元素的多个组件:

> which(x == "first" | x == "second" | x == "third")
j k l q r
1 2 3 8 9

返回的值显示列表中组件的数量及其名称。但是,有时我需要获取包含具有多个元素的字符向量的组件索引,例如mc("first", "second"))或nc("first", "second", "third"))。也就是说,组件中字符向量的长度将大于1.我认为以下方法可行:

which(x == c("first", "second"))

我错了,输出是:

j k
1 2
Warning message:
In x == c("first", "second") :
  longer object length is not a multiple of shorter object length

当我尝试使用多个条件时,情况相同:

> which(x == "first" | x == c("first", "second"))
j k q
1 2 8
Warning message:
In x == c("first", "second") :
  longer object length is not a multiple of shorter object length

which(x == c("first", "second"))的所需输出为:

m
4

which(x == "first" | x == c("first", "second"))的所需输出为:

j m q
1 4 8

如何做到这一点?没必要使用which,你......

P.S。如果你是downvote,请解释原因。

1 个答案:

答案 0 :(得分:3)

通过使用"list" == "character",“list”将转换为“{”作为as.character(x),我认为这是不需要的。您可以使用match来比较“list”对应的元素:

ff = function(x, table) which(setNames(table %in% x, names(table)))
ff(list("third"), x)
#l r 
#3 9 
ff(list("first", "second", "third"), x) # your "|"
#j k l q r 
#1 2 3 8 9 
ff(list(c("first", "second")), x)
#m 
#4 
ff(list("first", c("first", "second")), x) # your "|"
#j m q 
#1 4 8