user5409172
user5409172

Reputation:

Randomly extract a number of consecutive items from a sequence in R

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

Answers (2)

Angel Garcia Campos
Angel Garcia Campos

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)]
}

enter image description here

Upvotes: 0

Colonel Beauvel
Colonel Beauvel

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

Related Questions