Reputation:
Frag <- seq(1: 30000)
K <- 9
P <- sample(1:K,1)
sys.sample <- Frag[seq(P, length(Frag), K)]
Now sys.sample contains 3333 numbers. How do I randomly extract 16 consecutive items in R?
Upvotes: 3
Views: 1151
Reputation: 138
Putting @ColonelBeauvel's answer into a function would look like this
extractRandWindow <- function(x, p){
firstIndex = sample(seq(length(x) - p + 1), 1)
x[firstIndex:(firstIndex + p -1)]
}
Upvotes: 0
Reputation: 31161
If a vector v
has n
elements and you want to randomly extract p
consecutive elements (p<=n
), you can do:
possibleIndex = seq(length(v) - p + 1)
firstIndex = sample(possibleIndex, 1)
v[firstIndex:(firstIndex + p -1)]
Upvotes: 6