如何将元素插入到vector中?

我有一个逻辑向量,我希望在特定的索引处插入新的元素。 我已经提出了一个笨拙的解决scheme,但有一个更好的方法?

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) 

 [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE 

 print(probes.2) 

 [1] TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE [13] TRUE TRUE TRUE TRUE TRUE 

所以它的作品,但看起来很丑 – 有什么build议吗?

你可以用索引做一些魔术:

首先创build带有输出值的vector:

 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 

现在把戏。 每个老元素得到等级,每个新元素得到半等级

 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 

然后使用order按正确的顺序sorting:

 val[order(id)] # [1] TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE # [13] TRUE TRUE TRUE TRUE TRUE 

这些都是非常有创意的方法。 我认为与索引合作肯定是要走的路(马立克的解决scheme非常好)。

我只是提到有一个函数可以做到这一点: append()

 probes <- rep(TRUE, 15) probes <- append(probes, FALSE, after=5) probes <- append(probes, FALSE, after=11) 

或者你可以用你的索引recursion地做到这一点(你需要在每次迭代中增加“后”值):

 probes <- rep(TRUE, 15) ind <- c(5, 10) for(i in 0:(length(ind)-1)) probes <- append(probes, FALSE, after=(ind[i+1]+i)) 

顺便提一句, 这个问题以前也在R-Help上提过 。 正如巴里所说:

“其实我会说没有办法做到这一点,因为我不认为你实际上可以插入到vector – 你必须创build一个新的vector,产生插入的幻想!

这个怎么样:

 > 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 
 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 

一些时间:我的方法用户系统经过0.03 0.00 0.03

马立克方法用户系统经过0.18 0.00 0.18

R附加for循环用户系统经过1.61 0.48 2.10

这是一个棘手的问题。 这是一种方法。 它遍历列表,每次插入,所以它不是太高效。

 probes <- rep(TRUE, 15) probes.ind <- ind + 0:(length(ind)-1) for (i in probes.ind) { probes <- c(probes[1:i], FALSE, probes[(i+1):length(probes)]) } > probes [1] TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE [13] TRUE TRUE TRUE TRUE TRUE 

这应该甚至工作,如果IND有重复的元素,虽然IND确实需要sortingprobe.ind结构工作。

或者你可以使用miscTools包中的insertRow函数。

 probes <- rep(TRUE, 15) ind <- c(5,10) for (i in ind){ probes <- as.vector(insertRow(as.matrix(probes), i, FALSE)) }