从随机行开始的R数据帧中的随机样本选择

时间:2015-12-12 07:30:22

标签: r random row

我必须从数据框中随机选择特定间隔的行数。假设我必须从50行的数据帧中选择10行,我必须选择每5行。但我的出发点会随机变化,有时会是第8行甚至是第37行。以下是我正在使用的代码:

如果df是我的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), ]

问题是如果我从第37行开始,提取在第50行(我的df结束)停止,并且没有从第1行到第36行循环。不知道我是否必须使用for循环。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我们可以尝试

v1 <- c(randomRow:totRows, seq(randomRow-1))
df[v1[seq(1, length(v1), by = freq)],]