从随机行开始的 R 数据框中的随机样本选择
Random Sample selection in R data frame starting at a random row
我必须 select 以特定间隔从数据框中随机抽取一些行。假设如果我必须 select 10 行,从一个有 50 行的数据框中,我必须每 5 行 select。但我的起点会随机变化,比如有时会在第 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 循环。有人可以帮忙吗?
我们可以试试
v1 <- c(randomRow:totRows, seq(randomRow-1))
df[v1[seq(1, length(v1), by = freq)],]
我必须 select 以特定间隔从数据框中随机抽取一些行。假设如果我必须 select 10 行,从一个有 50 行的数据框中,我必须每 5 行 select。但我的起点会随机变化,比如有时会在第 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 循环。有人可以帮忙吗?
我们可以试试
v1 <- c(randomRow:totRows, seq(randomRow-1))
df[v1[seq(1, length(v1), by = freq)],]