[英]Finding Index of Common Elements in Multiple Vectors in R
From other stack overflow posts, I figured out the following code can be used to find the common values between multiple vectors (eg a, b): 从其他堆栈溢出帖子中,我发现以下代码可用于查找多个向量(例如a,b)之间的公共值:
Reduce(intersect, list(a,b,...))
I could not figure out a good way to get the common value indices from the vectors. 我想不出一种从向量中获取共同价值指数的好方法。 Any help would be appreciated.
任何帮助,将不胜感激。
Here is an example of the desired input and output: 这是所需输入和输出的示例:
a <- c(5,2)
b <- c(5,3)
d <- c(4,5)
Common value index between a and b should be 1, since both vectors have 5 at that index. a和b之间的公共价值指数应为1,因为两个向量在该指数处均具有5。 For finding common value index between a and d, the method should return 1 for a and 2 for d.
为了找到a和d之间的公共价值指数,该方法应该为a返回1,为d返回2。
a <- c(5,2); b <- c(5,3); d <- c(4,5)
mylist = list(a = a, b = b, d = d) #OR mylist = mget(c("a", "b", "d"))
common_values = Reduce(intersect, mylist)
lapply(mylist, function(x) which(x %in% common_values))
#$a
#[1] 1
#$b
#[1] 1
#$d
#[1] 2
It is not clear how you want to address when there can be more than one common value, but here is one way 目前尚不清楚在存在多个共同值时您要如何解决,但这是一种方法
a = 1:3
b = 2:4
d = c(2, 7, 3, 5)
mylist = mget(c("a", "b", "d"))
common_values = Reduce(intersect, mylist)
lapply(mylist, function(x)
sapply(setNames(common_values, common_values), function(y)
which(x %in% y)))
#$a
#2 3
#2 3
#$b
#2 3
#1 2
#$d
#2 3
#1 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.