Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用for循环索引需要很长时间?_R_For Loop - Fatal编程技术网

使用for循环索引需要很长时间?

使用for循环索引需要很长时间?,r,for-loop,R,For Loop,我正在运行这个for循环,没有任何问题,但它需要很长时间。我想使用apply family会更快,但不确定如何使用。有什么提示吗 set.seed(1) nrows <- 1200 ncols <- 1000 outmat <- matrix(NA, nrows, ncols) dat <- matrix(5, nrows, ncols) for (nc in 1 : ncols){ for(nr in 1 : nrows){ val <- dat[n

我正在运行这个
for循环
,没有任何问题,但它需要很长时间。我想使用apply family会更快,但不确定如何使用。有什么提示吗

set.seed(1)
nrows <- 1200
ncols <- 1000
outmat <- matrix(NA, nrows, ncols)
dat <- matrix(5, nrows, ncols)
 for (nc in 1 : ncols){
  for(nr in 1 : nrows){
    val <- dat[nr, nc]
    if(!is.na(val)){
      file <- readBin(dir2[val], numeric(), size = 4, n = 1200*1000)
      # my real data where dir2 is a list of files 
      # "dir2 <- list.files("/data/dir2", "*.dat", full.names = TRUE)"
      file <- matrix((data = file), ncol = 1000, nrow = 1200) #my real data

      outmat[nr, nc] <-  file[nr, nc]
    }

  }
}
set.seed(1)
nrows两种溶液

第一种方法会占用更多内存,但效率更高,而且我想如果您有24个文件,就像您所说的那样,这是可行的。一次读取所有文件,然后根据
dat
正确地子集。比如:

allContents<-do.call(cbind,lapply(dir2,readBin,n=nrows*ncol,size=4,"numeric")
res<-matrix(allContents[cbind(1:length(dat),c(dat+1))],nrows,ncols)
allContents两种解决方案

第一种方法会占用更多内存,但效率更高,而且我想如果您有24个文件,就像您所说的那样,这是可行的。一次读取所有文件,然后根据
dat
正确地子集。比如:

allContents<-do.call(cbind,lapply(dir2,readBin,n=nrows*ncol,size=4,"numeric")
res<-matrix(allContents[cbind(1:length(dat),c(dat+1))],nrows,ncols)

所有内容请您描述一下您的数据。不清楚为什么不将所有1200 x 1000作为单个块读取到内存中。你们有多少个这样的街区?我不使用bin文件(倾向于使用带有
read.table
fread
的csv文件),因此可能没有抓住要点。我不确定您是否有1200000个不同的文件,但您的循环需要很长时间,因为您实际上正在读取1200000个文件,并且磁盘访问速度非常慢。使用apply不会更快。如果您没有这么多文件,我建议您将流程还原为先读取每个文件并存储其数据,然后根据需要循环数据以进行处理。
dir2
中的几个文件有多少?请描述一下您的数据。不清楚为什么不将所有1200 x 1000作为单个块读取到内存中。你们有多少个这样的街区?我不使用bin文件(倾向于使用带有
read.table
fread
的csv文件),因此可能没有抓住要点。我不确定您是否有1200000个不同的文件,但您的循环需要很长时间,因为您实际上正在读取1200000个文件,并且磁盘访问速度非常慢。使用apply不会更快。如果您没有这么多文件,我建议您将流程还原为先读取每个文件并存储其数据,然后根据需要循环数据以处理它。dir2中的几个文件有多少?