# File to test commands in Chapter 7 of MacAnova Users' Guide
# Version of 010327
# 010327 added printname:F to getmacros calls
# Set default configuration
startTime <- gettime(quiet:T,keep:T)
setoptions(default:T)
DEGPERRAD <- 180/PI; E <- exp(1)
PLATFORM <- vecread(string:VERSION,bywords:T)[5]
MACINTOSH <- PLATFORM == "(Mac" || PLATFORM == "(Macintosh" ||\
	PLATFORM == "(Power"
DOS <- PLATFORM == "(DOS" || PLATFORM == "(Win32s"
if (MACINTOSH || DOS){ DATAPATH <- DATAPATHS <- HOME;;}
PATHSEP <- if (MACINTOSH){":"}else{"/"}
DATAFILE <- "macanova.dat"; MACROFILE <-  "macanova.mac"
MACROFILES <- vector("graphics.mac","regress.mac","design.mac",\
	"tser.mac", "arima.mac", "mulvar.mac", "math.mac", "macanova.mac")
setoptions(errors:20,dumbplot:T,height:25,width:80)
#7. Files
#7.1 Format of data readable by matread() and read()
datafile <- "y1               3     4
) Sample 3 by 4 matrix with 1 missing value
) MISSING -1
)) Comment line that will not normally be echoed
)) Such lines might give very extensive background information
)\"%f %f %f %f\"
  3.31662  3.00000  3.46410  3.31662
  3.16228  3.46410  2.00000 -1.00000
  2.44949  3.74166  2.82843  1.73205

y2               3     4 LOGICAL COLUMNS FORMAT
) This is the matrix (y1 > 3)
) MISSING -99
)\"5x%f %f %f\"
(5x,4f13.0)
Col.1            1            1            0
Col.2            0            1            1
Col.3            1            0            0
Col.4            1          -99            0

y3               2     2     4
) 2 by 2 by 2 array
) Rows in order are y3[1,1,],y3[1,2,],y3[2,1,],y3[2,2,]
) MISSING -99
)\"%f %f %f %f\"
 53.222   56.057   44.683   46.343
 36.147   56.357   47.651   54.889
 49.979   62.120  -99.000   35.926
 45.278   31.604   27.964   54.206

people           2     2 CHARACTER
) 2 by two matrix of unquoted CHARACTER elements with no embedded
) blanks or tabs
)\"%s %s\"
Tom              Harry            
Dick             Elizabeth                

experinfo       3 CHARACTER
) Each line of data is a CHARACTER element
Data were obtained in a randomized complete block experiment
in 7 replicates.  Treatments were control plus 3 levels of 
Nitrogen.

Desserts           3 QUOTED COLUMNS
) Data are quoted CHARACTER elements
)\"%s %s %s\"
\"Ice cream\" \"Strawberries\" \"Short cake
with whipped cream\"

nulldata    NULL
) This is a null data set.  It must be followed by a blank line

mystruc  2  STRUCTURE
) This is a structure with two components, a and b
) The blank line before the header of each component is required

mystruc$a  2 QUOTED COLUMNS
) CHARACTER vector of length 2
) Two quoted fields
\"The quick brown fox\" \"Jumps over the lazy dog\"

mystruc$constants  2 STRUCTURE
) This component is a structure with two components, pi and e

mystruc$constants$pi  1   1
) 1 by 1 matrix
3.14159265358979

mystruc$constants$e   1
) vector of length 1
2.71828182845905

labelled     4     3 COLUMNS LABELS NOTES
) Small REAL data set with one missing value coded as -99.
) Each line contains data for one column (COLUMNS on header)
) MISSING -99
) '4x' in the following format skips 4 characters (variable label)
)\"4x%f %f %f %f\"
Temp   34.5   45.2  23.1   20.1
Conc   .170   -99  .883    .401
Secs    3.5   4.7   3.2     5.8

labelled$LABELS    7   QUOTED COLUMNS
) Labels for sample data in quoted format by columns
)\"%s %s %s %s %s %s %s\"
\"@\" \"@\" \"@\" \"@\" \"Temp\" \"Conc\" \"Secs\"

labelled$NOTES     2 CHARACTER
) Notes for sampledata in \"by line\" format
Small REAL data set with row and column labels.
There is one missing value."
y <- matread(string:datafile, "y1") # ))' lines not echoed.
y <- matread(string:datafile, "y1", quiet:F) #echo '))' lines
#7.1.1 REAL and LOGICAL data
#7.1.2 CHARACTER data
#7.1.3 Structures
matread(string:datafile,"mystruc$constants$pi")
#7.1.4 Labels and notes
labelled <- read(string:datafile,"labelled")
labelled
getnotes(labelled) # see Sec. 8.9.1
read(string:datafile,"labelled$LABELS") # just read labels
read(string:datafile,"labelled$NOTES") # just read notes
#7.1.5 matread() and read() keywords
#7.2 Reading CHARACTER data from files
desserts <- matread(string:datafile,"Desserts") # or read(...)
desserts
chardata <- "#data on 2 children
Henry   Male   67.3,10.5
Susan   Female 59.2,15.1
    !
Other stuff ...
"
vecread(string:chardata,bywords:T,skip:"") # or character:T
words <- vecread(string:chardata,bywords:T,stop:"\377",skip:"")
words[-run(11)] # this time we got everything
words <- vecread(string:chardata,bywords:T,skip:"#",quiet:F)
words
lines <- vecread(string:chardata,bylines:T,skip:"#",quiet:T)
lines
chars <- vecread(string:chardata,bychars:T,skip:"#",quiet:T)
chars == vector("H","e","n","r","y"," "," "," ","M","a","l","e"," "," "," ",\
"6","7",".","3",",","1","0",".","5","\n","S","u","s","a","n"," ",\
" "," ","F","e","m","a","l","e"," ","5","9",".","2",",","1","5",\
".","1","\n"," "," "," "," ","!","\n","O","t","h","e","r"," ","s",\
"t","u","f","f"," ",".",".",".","\n")
#7.3  "Reading" from CHARACTER variables
x <- vecread(string:"1 3 2 7 10.11"); x
x <- vecread(string:vector("1 3","2 7","10.11"));x
charx1 <- "x1  1    5
) 1 by 5 matrix with up to 3 numbers per line
)\"%f %f %f \"
2 5 2
7 13.21"  # this is a single quoted string, a CHARACTER scalar
x1 <- matread(string:charx1,"x1")
x1
charx2 <- vector("x  1    5",\
") 1 by 5 matrix with up to 3 numbers per line",\
")\"%f %f %f \"","1 3 1","8 17.1") # this is a CHARACTER vector
x2 <- matread(string:charx2,"x")
x2
CLIPBOARD<-vector(292,366,347,310,326,334,332,348,309,325,\
312,340,330,327,317,313,335,334,321,336,\
317,314,336,339,333,333,326,325,326,332)
data <- matrix(vecread(string:CLIPBOARD),5)' # note transpose
data <- fromclip(5) # argument is number of columns
vecread(string:vector("Line 1","Line 2","Line 3"),bylines:T)
vecread(string:vector("ab","mn","yz"),bychars:T)
#7.3.1 Extracting information from a CHARACTER variable
VERSION
tmp <- vecread(string:VERSION,bywords:T);tmp #see Sec. 7.2
versionNo <- vecread(string:tmp[2]); versionNo
date <- vecread(string:tmp[4],silent:T); date
presidents <- "G. Washington  1789 1797 VA  2/22/1732 12/14/1799 Episcopalian
J. Adams       1797 1801 MA 10/30/1795   7/4/1826 Unitarian
T. Jefferson   1801 1809 VA  4/13/1743   7/4/1826 Deist"
data <- vecread(string:presidents,bylines:T) #See Sec. 7.2
data
names <- rep("",3) # create big enough variable
for(i,run(3)){ names[i] <- \
paste(vecread(string:data[i],bywords:T)[run(2)]);;}
# See Sec. 9.2.3 for for(...){...}; Sec. 8.3.1 for paste()
names
terms <- matrix(rep(0,6),3) # create matrix of right size
for(i,run(3)){ # Sec. 9.2.3
	@tmp <- vecread(string:data[i],bywords:T)[run(3,4)]
	terms[i,] <- vecread(string:@tmp)[run(2)]';;}
terms
birthyear <- rep(0,3) # create vector of right size
for(i,run(3)){
	@tmp <- vecread(string:data[i],bywords:T)[6]
	birthyear[i] <- vecread(string:@tmp,silent:T)[3];;}
birthyear
cmodel <- vecread(string:"y = a + b",bychars:T)
if (match("=", cmodel, 0) == 0){# See Sec. 9.2.2, 9.4.1
	print("ERROR: no \"=\" in the model")
} else {
	for (i,1,length(cmodel)){#See Sec. 9.2.3
		if(cmodel[i] == "="){break}
	}
	lhs <- if (i == 1) {""} else {cmodel[run(i-1)]}
	rhs <- if (i == length(cmodel)) {""} else {cmodel[-run(i)]}
	lhs[lhs == " "] <- ""; lhs <- paste(lhs,sep:"")
	rhs[rhs == " "] <- ""; rhs <- paste(rhs,sep:"")
	print(lhs,rhs) # See Sec. 7.4
}
#7.3.2 Finding ASCII codes for a CHARACTER variable - getascii()
getascii("ABCDE") # ascii code of 'A' is 65, etc.
getascii(vector("AB","C"), "DE") # same as preceding
getascii("\123")
getascii("\001\002\003\004\005") #or getascii("\1\2\3\4\5")
#7.4 Writing data to the screen and to files
a <- run(3);b <- sqrt(a)
matwrite(CONSOLE,a,b,logb:log(b),new:T) # was "myfile"
#7.4.1 print() and write()
x <- 1000*PI
print(x,format:"16.9g",x1:x,format:".4g",y:x,\
	format:"10.3f",z:x)
write(x)
print(sqrt(matrix(run(9),3)),header:F,labels:F)
print(vector(1,3,?,2.5,2))
print(vector(1,3,?,2.5,2),missing:"??")
print(sqrt(matrix(run(9),3)),file:CONSOLE,new:T)
print(sqrtpi:sqrt(PI))
print(name:"Square root of pi",sqrt(PI),name:"Log(pi)",log(PI))
print(x,header:F,labels:F,file:CONSOLE,new:T) # or write()
#7.4.2 matprint() and matwrite()
x <- run(5); y <- vector(1,2,3,5,8)
matwrite(CONSOLE,sqrtx:sqrt(x'),logy:log(y'),\
	format:"8.6f") #was mydata.txt
y <- sqrt(matrix(vector(11,10,6,9,12,14,12,4,8,11,?,3),3))
matprint(CONSOLE,missing:-1,y) # print to screen (CONSOLE)
matwrite(CONSOLE,y,format:"9.5f",missing:-99,ysq:y^2)
matprint(CONSOLE,missing:-1,y,header:F)
matprint(CONSOLE,missing:-1,y,sep:",") # comma-separated
matprint(CONSOLE,missing:-1,y,sep:"\t") # Tab-separated
matprint(CONSOLE,name:"sqrt(data)",y,missing:-99)
matprint(CONSOLE,y,missing:-99,\
	comments:vector("Sample data","which includes 1 MISSING value"))
#7.4.3 putascii()
putascii(7,7,7) # rings bell or "beeps" 3 times
putascii(run(65,90)) # uppercase alphabet
putascii(77,97,99,65,110,111,118,97)
getascii(putascii(run(30,34),keep:T))
putascii(getascii("MacAnova"),keep:T)
#7.5 Macro files
#7.5.1 macroread(), read() and the format of macro files
covarfile <- "mulvar.mac" # used to be "macanova.mac"
compcovar <- macroread(covarfile,"covar")
compcovar <- macroread(covarfile,"covar",quiet:T)
macrofile <- "fences        8 MACRO
) macro with line count on the name line
) usage: d <- fences(x), compute inner and outer
)    fences of vector x
)) This is a comment that will not be echoed unless quiet:F is used
)) Such lines can be used to include extensive documentation that
)) it would not be desirable to echo whenever read.
# usage: d <- $S(x)
@x$$ <- $1
if (!isvector(@x$$) || !isreal(@x$$)){
	error(\"ERROR: $1 is not a REAL vector\")}
@stats$$ <- describe($1, q1:T, q3:T)
@iqr$$ <- @stats$$$q3 - @stats$$$q1
vector(@stats$$$q1 - vector(3, 1.5)*@iqr$$,\\
   @stats$$$q3 + run(1.5, 3)*@iqr$$)

standardize MACRO OUTOFLINE
) macro with no line count but with special line to terminate it
) usage: d <- standardize(x)
# usage: d <- $S(x)
@x$$ <- $1
@dims$$ <- dim(@x$$)
@dims$$[1] <- 1
@mean$$ <- array(describe(@x$$,mean:T),@dims$$)
@sd$$ <- sqrt(array(describe(@x$$,var:T),@dims$$))
(@x$$ - @mean$$)/@sd$$
%standardize%"
#7.5.2 macrowrite()
getmacros(colplot,rowplot,quiet:T,printname:F)
macrowrite(CONSOLE,colplot,rowplot) 
macrowrite(CONSOLE,colplot,oldstyle:T)
#macrowrite("trnsform.mac",transform:mymacro)
#7.5.3 getmacros
MACROFILES # default value
getmacros(groupcovar,detrend)
getmacros(groupcovar,detrend,quiet:T,printname:F)
#7.5.4 addmacrofile
MACROFILES # here is the current default list
addmacrofile("survival.mac") # add file name at start
MACROFILES # updated list
addmacrofile("multivar.mac",T) # add file name at end
MACROFILES # updated list
#7.6 Executing commands in a file - batch()
batch("mybatch.txt") # initiate executing commands in file
batch("mybatch.txt",echo:F) # echoing of commands suppressed
#7.7  Additional options on save() and restore()
save("variable.sav",names,terms,birthyear)#or asciisave(...)
save("workspac.sav",all:T) # or asciisave("workspac.asc",all:T)
restore("workspac.sav")
coefs()$x2 # works because all:T used when saving
delete(birthyear) # birthyear was saved on variable.sav
restore("variable.sav", delete:F)
list(birthyear,y) # birthyear restored, y still there
getoptions(restoredel:T) # default value of restoredel is T
setoptions(restoredel:F) # change it to F
restore("variable.sav") # note absence of delete:F
list(y) # y not deleted
restore("variable.sav", delete:F,list:T)
#7.8 Customizing MacAnova
#7.8.1 Using a start up file
#7.8.2 Environmental variable MACANOVA
print(paste("Total time =",gettime(quiet:T,keep:T) - startTime))
