我有一个逻辑向量,我希望在特定索引处插入新元素.我在下面提出了一个笨拙的解决方案,但有更简洁的方法吗?
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)
所以它有效,但看起来很难看 - 有什么建议吗?
Sha*_*ane 69
这些都是非常有创意的方法.我认为使用索引肯定是要走的路(Marek的解决方案非常好).
我只想提一下,有一个功能可以做到:append().
probes <- rep(TRUE, 15)
probes <- append(probes, FALSE, after=5)
probes <- append(probes, FALSE, after=11)
Run Code Online (Sandbox Code Playgroud)
或者您可以使用索引递归执行此操作(您需要在每次迭代时增加"after"值):
probes <- rep(TRUE, 15)
ind <- c(5, 10)
for(i in 0:(length(ind)-1))
probes <- append(probes, FALSE, after=(ind[i+1]+i))
Run Code Online (Sandbox Code Playgroud)
顺便提一下,此问题之前也曾在R-Help上提出过.正如巴里所说:
"实际上我会说没有办法做到这一点,因为我不认为你实际上可以插入一个向量 - 你必须创建一个新的向量,产生插入错觉!"
Mar*_*rek 35
你可以用索引做一些魔术:
首先使用输出值创建向量:
probs <- rep(TRUE, 15)
ind <- c(5, 10)
val <- c( probs, rep(FALSE,length(ind)) )
# > val
# [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
# [13] TRUE TRUE TRUE FALSE FALSE
Run Code Online (Sandbox Code Playgroud)
现在骗局.每个旧元素获得排名,每个新元素获得一半排名
id <- c( seq_along(probs), ind+0.5 )
# > id
# [1] 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 15.0
# [16] 5.5 10.5
Run Code Online (Sandbox Code Playgroud)
然后使用order按正确的顺序排序:
val[order(id)]
# [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)
这个怎么样:
> probes <- rep(TRUE, 15)
> ind <- c(5, 10)
> probes.ind <- rep(NA, length(probes))
> probes.ind[ind] <- FALSE
> new.probes <- as.vector(rbind(probes, probes.ind))
> new.probes <- new.probes[!is.na(new.probes)]
> new.probes
[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)
probes <- rep(TRUE, 1000000)
ind <- c(50:100)
val <- rep(FALSE,length(ind))
new.probes <- vector(mode="logical",length(probes)+length(val))
new.probes[-ind] <- probes
new.probes[ind] <- val
Run Code Online (Sandbox Code Playgroud)
一些时间:我的方法用户系统已经过了0.03 0.00 0.03
Marek方法用户系统经过0.18 0.00 0.18
R附加for循环用户系统已过1.61 0.48 2.10