在for循环中删除一行一行

时间:2014-05-05 19:59:32

标签: r for-loop lapply

我有一个大字符向量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)

4 个答案:

答案 0 :(得分:1)

使用list代替c。然后,您可以将值设置为NULL,它们将被删除。

file[file %in% rand_no] <- NULL这会在rand_no中找到file中的所有实例并将其删除。

file <- list("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 <- sample(file, 2)

library(car) #From poster's code.

file[file %in% rand_no] <- NULL

如果您正在处理大量文件,使用%in%比较字符串可能会让您陷入困境。在那种情况下,我会使用索引。

file <- list("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 <- sample(1:length(file), 2)

library(car) #From poster's code.

file[rand_no] <- NULL

答案 1 :(得分:1)

Sample()已经按照置换顺序返回值而没有替换(除非你设置replace = T)。所以它永远不会选择两次值。

因此,如果你想要三组100个不共享任何元素的样本,你可以使用

file <- rep(1:10000)
rand_no <- sample(seq_along(file), 300)

s1<-file[rand_no[1:100]]
s2<-file[rand_no[101:200]]
s3<-file[rand_no[201:300]]

或者,如果您希望每次可以减少100的总大小

s1<-file[-rand_no[1:100]]
s2<-file[-rand_no[1:200]]
s3<-file[-rand_no[1:300]]

答案 2 :(得分:0)

一种简单的方法是选择随机索引,然后删除这些索引:

file <- 1:10000  # Build sample data
ind <- sample(seq(length(file)), 100)  # Select random indices
rand_no <- file[ind]  # Compute the actual values selected
file <- file[-ind]  # Remove selected indices

答案 3 :(得分:0)

我认为使用samplesplit可能是一种很好的方法,无需更改files变量。我不是变异的忠实粉丝,除非你真的需要,这会让你确切地知道你用于每个分析块的文件。

files<-paste("file",1:100,sep="_")     
randfiles<-sample(files, 50)
randfiles_chunks<-split(randfiles,seq(1,length(randfiles), by=10))