User:AnatolV/Helper Functions

From Rosetta Code
Revision as of 04:34, 2 April 2017 by rosettacode>AnatolV (adding R HFs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

R Helper Functions

Note
  • All plotting helper functions are using matrix mat or 2 vectors X,Y from the dump file created by plotmat().
  • The file names used are without extension (which will be added as ".png", ".dmp" and ".dat" when needed).
  • Requesting dump file is useful if the generating/plotting time is big. Having a dump file makes it easy and fast to repeat plotting with different colors, titles, etc.
  • If number of generated dots is very big then plotting from a dump file could be very slow too. Actually, plotv2() shows almost "pure" plotting time.
Works with: R version 3.3.1 and above

<lang r>

  1. plotmat(): Simple plotting using matrix mat (filled with 0/1). v. 8/31/16
  2. Where: mat - matrix; fn - file name; clr - color; ttl - plot title;
  3. dflg - writing dump file flag (0-no/1-yes): psz - picture size.

plotmat <- function(mat, fn, clr, ttl, dflg=0, psz=600) {

 m <- nrow(mat); d <- 0;
 X=NULL; Y=NULL;
 pf = paste0(fn, ".png"); df = paste0(fn, ".dmp");
 for (i in 1:m) {
   for (j in 1:m) {if(mat[i,j]==0){next} else {d=d+1; X[d] <- i; Y[d] <- j;} }
 };
 cat(" *** Matrix(", m,"x",m,")", d, "DOTS\n");
 # Dumping if requested (dflg=1).
 if (dflg==1) {dump(c("X","Y"), df); cat(" *** Dump file:", df, "\n")};
 # Plotting
 plot(X,Y, main=ttl, axes=FALSE, xlab="", ylab="", col=clr, pch=20);
 dev.copy(png, filename=pf, width=psz, height=psz);
 # Cleaning 
 dev.off(); graphics.off();

}

  1. plotv2(): Simple plotting using 2 vectors (dumped into ".dmp" file).
  2. Where: fn - file name; clr - color; ttl - plot title; psz - picture size.
  3. v. 8/31/16

plotv2 <- function(fn, clr, ttl, psz=600) {

 cat(" *** START:", date(), "clr=", clr, "psz=", psz, "\n");
 cat(" *** File name -", fn, "\n");
 pf = paste0(fn, ".png"); df = paste0(fn, ".dmp");
 source(df);
 d <- length(X);
 cat(" *** Source dump-file:", df, d, "DOTS\n");
 cat(" *** Plot file -", pf, "\n");
 # Plotting
 plot(X, Y, main=ttl, axes=FALSE, xlab="", ylab="", col=clr, pch=20);
 # Writing png-file
 dev.copy(png, filename=pf, width=psz, height=psz);
 # Cleaning 
 dev.off(); graphics.off();
 cat(" *** END:", date(), "\n");

} </lang>