【发布时间】:2014-05-05 19:59:31
【问题描述】:
我有一个大字符向量file,我需要从中抽取一个随机样本。这工作正常。但我需要一个接一个地抽取样本。为此,我想通过已经从中提取的每个元素来缩短 file(我可以绘制一个新样本而无需多次绘制相同的元素)。
我有一些解决方案,但我对其他可能更快、甚至更重要的方法感兴趣,也许是正确的。
这是我的尝试:
方法 1
file <- rep(1:10000)
rand_no <- sample(file, 100)
library(car)
a <- data.frame()
for (i in 1:length(rand_no)){
a <- rbind(a, which.names(rand_no[i], file))
file <- file[-a[1,1]]
}
问题:
Warning message:
In which.names(rand_no[i], file) : 297 not matched
方法 2
file <- rep(1:10000)
rand_no <- sample(file, 100)
library(car)
deleter <- function(i) {
a <- which.names(rand_no[i], file)
file <- file[-a]
}
lapply(1:length(rand_no), deleter)
问题:
这根本行不通。也许我应该拆分问题,因为第二个问题显然在于我没有完全理解lapply。
感谢您的任何建议。
编辑
我希望它适用于数字,但当然file 看起来像这样:
file <- c("Post-19960101T000000Z-1.tsv", "Post-19960101T000000Z-2.tsv", "Post-19960101T000000Z-3.tsv","Post-19960101T000000Z-4.tsv", "Post-19960101T000000Z-5.tsv", "Post-19960101T000000Z-6.tsv", "Post-19960101T000000Z-7.tsv","Post-19960101T000000Z-9.tsv")
当然rand_no 不能超过 100 个文件,样本如此之少。因此:
rand_no <- sample(file, 2)
【问题讨论】: