使用索引省略条件

时间:2015-06-09 23:52:52

标签: r

是否可以对矢量进行采样但跳过特定指数?

expl <- c("This","is","an","example","One","Two","Three")
skipIdx <- c(1, 4)

示例使“”和“示例”始终位于其原始位置 1 4

谢谢

2 个答案:

答案 0 :(得分:4)

weirdsamp <- function(vec, skip) {vec2<-numeric(length(vec))
                           vec2[skip] <- vec[skip]
                           vec2[ -skip]<- sample(vec[-skip])
                           vec2}

> weirdsamp(expl, skipIdx)
[1] "This"    "One"     "is"      "example" "an"      "Two"     "Three"  
> weirdsamp(expl, skipIdx)
[1] "This"    "is"      "Three"   "example" "an"      "Two"     "One"    
> weirdsamp(expl, skipIdx)
[1] "This"    "an"      "is"      "example" "Two"     "Three"   "One"    

我认为这可以大大缩短:

weirdsamp <- function(vec, skip) { vec[ -skip]<- sample(vec[-skip]); vec}

答案 1 :(得分:2)

只是对未跳过的索引进行采样。

设置示例:

expl <- c("This","is","an","example","One","Two","Three")
skipIdx <- c(1, 4)

现在示例:

nonskip <- seq_along(expl)[-skipIdx]  ## indices to sample
expl2 <- expl                         ## copy
set.seed(101)                         ## for reproducibility
expl2[nonskip] <- expl2[sample(nonskip)]
expl2
## [1] "This"    "an"      "Three"   "example" "One"     "is"      "Two"