我需要从280万行的csv数据集中抽取100,000-200,000行的随机样本。我如何有效地做到这一点,以便可以清洁和处理随机样本?
在this.dialog.open(ErrorDialogComponent, { data: message });
库中,我使用了DMwR2
函数,但是输出数据弄乱了我需要使用的22个变量。
sampleCSV
数据集来源:https://www.kaggle.com/pschale/mlb-pitch-data-20152018#pitches.csv
library(caret)
library(DMwR2)
我希望pitchData <- sampleCSV(file.choose(), 200000, 2867154 , header = TRUE , mxPerc = 0.5)
summary(pitchData)
的输出具有与csv文件相同的变量名,但是它将使用随机数重命名它们,并且某些变量会丢失。
答案 0 :(得分:0)
也许以下功能可以完成问题的要求。请注意,它使用包R.utils
中的函数。
返回值是一个包含2个成员的列表:
lines
读入的行号; data
数据框。可以更改为仅返回数据帧。
sample_csv <- function(fname, n, sep = ",", header = TRUE, ...){
N <- R.utils::countLines(fname)
stopifnot(N >= n)
lns <- sample(N, n)
x <- sapply(lns, function(l){
scan(fname, what = character(), skip = l - 1, nlines = 1, quiet = TRUE)
})
list(lines = lns,
data = read.table(textConnection(x),
sep = sep, header = header, ...)
)
}
set.seed(1234)
res <- sample_csv(filename, 100, header = FALSE)
str(res$data)