R:如何采样
R: how to sample
我有一个关于如何采样的问题
我有一个名为 'inventory' 的数据框,看起来像这样(1000 行)
inventory_date number_purchases
1 1/1/1986 20
2 2/4/1992 15
3 12/13/2001 10
我想对其中的 5 行进行抽样
这是我的代码
samplesize <- c(5,10,15,20,25)
for (m in 1:length(samplesize))
{
mysample <- sample(inventory, samplesize[m], replace=FALSE)
}
当我 运行 代码时,它采用 1000 而不是 5、10、15 等的样本。它忽略了 samplesize[m] 为什么?我的代码有什么问题?
看起来很简单。
在你的例子中,你实际上并不想生成随机数据,因为你已经有了它。相反,您想以随机方式从数据框中抽取 5 行。试试这个代码:
// generate 5 random row indices
random.indices <- sample(1:nrow(inventory), 5, replace=FALSE)
// use these random indices to access rows from your data frame
for (m in 1:5) {
sample.row <- inventory[random.indices[m], ]
// use this random row in your calculation
}
我有一个关于如何采样的问题
我有一个名为 'inventory' 的数据框,看起来像这样(1000 行)
inventory_date number_purchases
1 1/1/1986 20
2 2/4/1992 15
3 12/13/2001 10
我想对其中的 5 行进行抽样
这是我的代码
samplesize <- c(5,10,15,20,25)
for (m in 1:length(samplesize))
{
mysample <- sample(inventory, samplesize[m], replace=FALSE)
}
当我 运行 代码时,它采用 1000 而不是 5、10、15 等的样本。它忽略了 samplesize[m] 为什么?我的代码有什么问题?
看起来很简单。
在你的例子中,你实际上并不想生成随机数据,因为你已经有了它。相反,您想以随机方式从数据框中抽取 5 行。试试这个代码:
// generate 5 random row indices
random.indices <- sample(1:nrow(inventory), 5, replace=FALSE)
// use these random indices to access rows from your data frame
for (m in 1:5) {
sample.row <- inventory[random.indices[m], ]
// use this random row in your calculation
}