Hi all,

I have just encountered a weird behavior of image(sparseMatrix) when trying to output plots to files in a for loop.

A sample code is provided below at the end of this mail as well as in the attachment. In the code, calling image(sparseMatrix) works outside of a for loop - the image file is written. Calling image(as.matrix(sparseMatrix)) also works inside a for loop thus eliminating file access problem. However when using image(sparseMatrix) inside for loop, no image file is produced, nor is there any error message.

The execution environment is on 2 different distributions of Linux running R 3.6.3 and 4.2.1, Matrix library 1.2-18 and 1.5-3 respectively, and all showing the same behavior.

Can anyone point me a direction on where to look for?

Sincerely,

Shunran Zhang

--- Sample code ---

# Initialize dataset library(Matrix) set.seed(0) filler <- list(sample(1:1000,1000), sample(1:1000,1000), runif(1000,0,100)) sampledata <- sparseMatrix(i = filler[[1]], j = filler[[2]], x = filler[[3]], dims = c(1000,1000)) # Works: image on a sparse matrix outside for loop item <- "a" png(paste("img/out_of_for_",item,".png", sep = "", collapse = ""), width = 1000, height = 1000) image(sampledata) dev.off() remove(item) for(item in c("a")){  # Does not work: image on a sparse matrix inside for loop  png(paste("img/in_for_img_",item,".png", sep = "", collapse = ""), width = 1000, height = 1000)  image(sampledata)  dev.off()  # Works: image on a dense matrix inside for loop  png(paste("img/in_for_hist_",item,".png", sep = "", collapse = ""), width = 1000, height = 1000)  image(as.matrix(sampledata))  dev.off() }
#!/usr/bin/Rscript --vanilla

# Initialize dataset
library(Matrix)
set.seed(0)
filler <- list(sample(1:1000,1000), sample(1:1000,1000), runif(1000,0,100))
sampledata <- sparseMatrix(i = filler[[1]], j = filler[[2]], x = filler[[3]], 
dims = c(1000,1000))

# Works: image on a sparse matrix outside for loop
item <- "a"
png(paste("img/out_of_for_",item,".png", sep = "", collapse = ""), width = 
1000, height = 1000)
image(sampledata)
dev.off()
remove(item)

for(item in c("a")){
  # Does not work: image on a sparse matrix inside for loop
  png(paste("img/in_for_img_",item,".png", sep = "", collapse = ""), width = 
1000, height = 1000)
  image(sampledata)
  dev.off()
  # Works: image on a dense matrix inside for loop
  png(paste("img/in_for_hist_",item,".png", sep = "", collapse = ""), width = 
1000, height = 1000)
  image(as.matrix(sampledata))
  dev.off()
}
______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to