我有一个类似于以下内容的清单:
> 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返回的值显示列表中组件的数量及其名称。但是,有时我需要获得包含多个元素(如m (c("first", "second"))或n (c("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 lengthwhich(x == c("first", "second"))的期望输出是:
m
4which(x == "first" | x == c("first", "second"))的期望输出是:
j m q
1 4 8这是怎么做到的?不用用which,你.
发布于 2015-11-22 13:57:53
通过使用"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 https://stackoverflow.com/questions/33855104
复制相似问题