r - R:在另一个向量中查找向量的索引(如果存在)
问题描述
我想知道一个向量在另一个向量中的起始索引。例如,forc(1, 1)
和c(1, 0, 0, 1, 1, 0, 1)
它将是 4。
重要的是我想寻找完全相同的向量。因此,对于c(1, 1)
insidec(1, 0, 1, 1, 1, 0)
它是 FALSE as c(1, 1) != c(1, 1, 1)
。
现在我正在检查短向量是否包含在长中,如下所示:
any(with(rle(longVec), lengths[as.logical(values)]) == length(shortVec)
但我不知道如何确定它的索引......
解决方案
此功能应该起作用:
my_function <- function(x, find) {
# we create two matrix from rle function
m = matrix(unlist(rle(x)), nrow=2, byrow = T)
n = matrix(unlist(rle(find)), nrow=2, byrow = T)
# for each column in m we see if its equal to n
temp_bool = apply(m, 2, function(x) x == n) # this gives a matrix of T/F
# then we simply sum by columns, if we have at least a 2 it means that we found (1,1) at least once
temp_bool = apply(temp_bool, 2, sum)
# updated part
if (any(temp_bool==2)) {
return(position = which(temp_bool==2)+1)
} else {
return(position = FALSE)
}
}
my_function(x, find)
#[1] 4
my_function(y, find)
#[1] FALSE
为了在这里更清楚,我展示了这两个的结果apply
:
apply(m, 2, function(x) x == n)
# [,1] [,2] [,3] [,4] [,5]
# [1,] FALSE TRUE TRUE FALSE FALSE
# [2,] TRUE FALSE TRUE FALSE TRUE # TRUE-TRUE on column 3 is what we seek
apply(temp_bool, 2, sum)
#[1] 1 1 2 0 1
示例数据:
x <- c(1,0,0,1,1,0,1)
y <- c(1,0,1,1,1,0)
find <- c(1,1) # as pointed this needs to be a pair of the same number
推荐阅读
- xcode - gfortran ld:找不到-lSystem的库
- java - 安排 Cronjob 更改运行时 - JAVA
- pandas - 如何通过 dtypes 过滤行?
- flutter - Flutter:如何为按下的每个网格项导航到另一个屏幕
- amazon-web-services - 我们可以在部署到 Elastic Beanstalk 时指定 Dockerfile 路径吗?
- c# - 如何将射击分配给特定键?
- php - Laravel 在哪里或哪里
- javascript - 在页面之间发送值反应原生钩子
- html - Dompdf中表格垂直对齐中间的问题
- reactjs - 子组件中明确存在的上下文属性未定义