vendredi 11 décembre 2015

Random Sample selection in R data frame starting at a random row

I have to select a number of rows at specific intervals from a data frame randomly. Suppose if I have to select 10 rows, from a data frame with 50 rows, I have to select every 5th row. But my starting point will vary randomly, say sometime it will be 8th row or even 37th row. The following is the code I am using:

if df is my data.frame:

randomRow <- 37       #assuming I am starting at the 37th row
nofRows <- 5          #number of rows that I have to select out of 50 rows
totRows <- nrow(df)
freq <- as.numeric(format(round(totRows/nofRows), nsmall = 0))       #calculating the frequency interval

#code to subset

df[seq(randomRow, nrow(df), freq), ]

The problem is if I start at 37th row the fetch stops at 50th row (end of my df), and is not looping around from 1st row to 36th row. Don't know if I have to use a for loop. Can someone help?




Aucun commentaire:

Enregistrer un commentaire