我有一个逻辑向量,我希望在特定索引处插入新元素.我在下面提出了一个笨拙的解决方案,但有更简洁的方法吗?
probes <- rep(TRUE, 15)
ind <- c(5, 10)
probes.2 <- logical(length(probes)+length(ind))
probes.ind <- ind + 1:length(ind)
probes.original <- (1:length(probes.2))[-probes.ind]
probes.2[probes.ind] <- FALSE
probes.2[probes.original] <- probes
print(probes)
Run Code Online (Sandbox Code Playgroud)
给
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
Run Code Online (Sandbox Code Playgroud)
和
print(probes.2)
Run Code Online (Sandbox Code Playgroud)
给
[1] TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE
[13] TRUE TRUE TRUE TRUE TRUE
Run Code Online (Sandbox Code Playgroud)
所以它有效,但看起来很难看 - 有什么建议吗?
我有两个整数向量,对于第二个向量的每个元素,我想找到第一个向量的任何元素的最小距离 - 例如
obj1 <- seq(0, 1000, length.out=11)
obj2 <- 30:50
min_diff <- sapply(obj2, function(x) min(abs(obj1-x)))
min_diff
Run Code Online (Sandbox Code Playgroud)
回报
[1] 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
Run Code Online (Sandbox Code Playgroud)
有更有效的方法吗?我想把它扩展到数千(百万?)的obj1和obj2.
谢谢你,亚伦
r ×2