从更大的基于excel的数据集中提取R中的x行数

问题描述 投票:0回答:2

如何使用R而不替换从具有百万行的Excel数据集中选择x(= 1000)行数并将此数据作为新数据集?

r statistics
2个回答
0
投票

有许多用于读取XLSX文件的库。我会在这里使用readxl,但我想这对于这个具体案例来说和其他任何东西一样好。您还需要使用set.seed来确保每次执行时随机样本都相同。

# Read XLSX file
require(readxl)
df <- read_excel("~/Desktop/yourfile.xlsx")

set.seed(123);
df[sample(1:nrow(df), 1000, replace = F),]

0
投票

这是一种使用openxlsx::read.xlsx()的方法,允许用户使用样本ID来指定从传入电子表格中读取的行。这样,您只需要读取1,000行而不是仅读取1,000,000行,以便除了1,000行以外的所有子行。

readxl::read_excel()目前没有此功能。

set.seed(90514327)
# create a sample of 1,000 items from 1,000,000
theRows <- sample(1:1000000,1000)

# read excel file using theRows to select the rows being read
# assume first row is header labels, therefore, add 1 to theRows
theRows <- theRows + 1
library(openxlsx)
theData <- read.xlsx("fileName.xlsx",rows=theRows,header=TRUE)

更新2017年12月17日:根据评论,OP需要读取CSV文件,而不是Excel文件。因此需要不同的技术。 read.csv()没有类似于openxlsx::read.xlsx()的功能,允许用户指定要从文件中读取的行向量。因此,必须读取整个文件并将其子集化。

为了重现性,我将生成一百万行和10列数据,使用write.csv()将它们写入磁盘,并使用readr::read_csv()和提取运算符[readr::read_csv()跑得比base::read.csv()快得多。

system.time(x <- matrix(runif(10000000),nrow=1000000,ncol=10))
x <- as.data.frame(x)
system.time(write.csv(x,"./data/random.csv",row.names=FALSE))
# create a sample of 1,000 items from 1,000,000
theRows <- sample(1:1000000,1000)
# now use readr::read_csv
library(readr)
system.time(x <- read_csv("./data/random.csv")[theRows,])
nrow(x)

......和输出:

> system.time(x <- matrix(runif(10000000),nrow=1000000,ncol=10))
   user  system elapsed 
  0.366   0.060   0.427 
> x <- as.data.frame(x)
> system.time(write.csv(x,"./data/random.csv",row.names=FALSE))
   user  system elapsed 
 12.444   0.171  12.745 
> # create a sample of 1,000 items from 1,000,000
> theRows <- sample(1:1000000,1000)
> # now use readr::read_csv
> library(readr)
> system.time(x <- read_csv("./data/random.csv")[theRows,])
Parsed with column specification:
cols(
  V1 = col_double(),
  V2 = col_double(),
  V3 = col_double(),
  V4 = col_double(),
  V5 = col_double(),
  V6 = col_double(),
  V7 = col_double(),
  V8 = col_double(),
  V9 = col_double(),
  V10 = col_double()
)
|==================================================================| 100%  171 MB
   user  system elapsed 
  3.289   0.632   4.750 
> nrow(x)
[1] 1000
> 

使用read.csv()代替

以下是与read.csv()相同操作的性能时间。

> # for comparison, read.csv timing
> system.time(x <- read.csv("./data/random.csv")[theRows,])
   user  system elapsed 
 51.921   0.818  53.231 
> nrow(x)
[1] 1000
> 

是的,使用read.csv()readr::read_csv()读取文件需要多10倍的时间。

硬件规格

性能时序在具有以下配置的MacBook Pro上运行。

  • 操作系统:macOS 10.13.2(17C88)
  • 处理器:Intel i5为2.6Ghz,turbo高达3.3Ghz,两个内核
  • 内存:8千兆字节
  • 磁盘:512千兆字节,固态硬盘
  • 建成日期:2013年4月
  • © www.soinside.com 2019 - 2024. All rights reserved.