在列表中查找矢量元素的索引 [英] Find indices of vector elements in a list
问题描述
我有这个玩具角色向量:
I have this toy character vector:
a = c("a","b","c","d","e","d,e","f")
其中某些元素用逗号(例如"d,e")连接起来
in which some elements are concatenated with a comma (e.g. "d,e")
以及包含该向量的唯一元素的列表,在这种情况下,如果使用逗号串联元素,则我不会保留它们的各个组成部分.
and a list that contains the unique elements of that vector, where in case of comma concatenated elements I do not keep their individual components.
这是列表:
l = list("a","b","c","d,e","f")
我正在寻找一种有效的方法来获取l
列表中a
的元素的索引.对于a
中由逗号连接的元素表示的a
元素,它应返回l
中这些逗号连接的元素的索引.
I am looking for an efficient way to obtain the indices of the elements of a
in the l
list. For elements of a
that are represented by the comma concatenated elements in l
it should return the indices of the these comma concatenated elements in l
.
因此此函数的输出为:
c(1,2,3,4,4,4,5)
如您所见,它返回a
元素的索引4:"d","e"和"d,e"
As you can see it returns index 4 for a
elements: "d", "e", and "d,e"
推荐答案
您可以将策略与因素结合使用.首先,使用
You could use a strategy with factors. First, find the index for each element in your list with
l <- list("a","b","c","d,e","f")
idxtr <- Map(function(x) unique(c(x, strsplit(x, ",")[[1]])), unlist(l))
这将为l
中的每个项目建立一个列表,以及每个元素的所有可能匹配项.然后我们取向量a
并用这些水平创建一个因子,然后根据我们刚刚构建的列表重新分配
This build a list for each item in l
along with all possible matches for each element. Then we take the vector a
and create a factor with those levels, and then reassign based on the list we just build
a <- c("a","b","c","d","e","d,e","f")
a <- factor(a, levels=unlist(idxtr));
levels(a) <- idxtr
as.numeric(a)
# [1] 1 2 3 4 4 4 5
最后,要获取索引,我们在因子上使用as.numeric
finally, to get the index, we use as.numeric on the factor
这篇关于在列表中查找矢量元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!