
#############
## Comandos de Bajo Nivel
#############

attach(mtcars)
plot(disp, mpg, type='n',axes=F)
points(disp[cyl==4], mpg[cyl==4], pch=16, col=2)
points(disp[cyl==6], mpg[cyl==6], pch=17, col=3)
points(disp[cyl==8], mpg[cyl==8], pch=18, col=4)
axis(1)
axis(4)
title('Consumo de Combustible', 1974)
arrows(470, 15, 470, 12, code = 2)
text(475, 17, 'menor\nrendimiento',font=3,adj=1)
arrows(100,34, 140,34, code=1)
text(225, 34, 'mayor rendimiento', font=2)
leg.txt <- c('4 cil.', '6 cil.', '8 cil.')
legend(350,32, leg.txt,col=2:4, pch=16:18)


#############
## Parametros Graficos
#############

par()

plot(cars)
oldpar <- par(bg=0, bty='o', cex=1, col='black', font=1, lty='solid', lwd=1, pch=1) 
par(bg=7, bty='7', cex=1.5, col='blue', font=2, lty='dashed', lwd=2, pch=3) 
plot(cars)
plot(iris)
par(oldpar)
plot(cars)

#################
## Ventanas Graficas
#################

windows(); pdf(); postscript()
dev.list()

dev.cur()
dev.set(3)
dev.off(5)
dev.off(4)

#############
## Division
#############

mat <- matrix(1:4,2,2)
mat 
layout(mat)
layout.show(4)

layout(matrix(1:6,3,2))
layout.show(6)
layout(matrix(1:6,2,3))
layout.show(6)
layout(matrix(1:6,3,2,byrow=TRUE))
layout.show(6)

(m <- matrix(c(1:3,3), 2, 2))
layout(m)
layout.show(3)

m <- matrix(1:4, 2, 2)
layout(m, widths=c(1,3), heights=c(3,1))
layout.show(4)

m <- matrix(c(1,1,2,1), 2, 2)
layout(m, widths=c(2,1), heights=c(1,2))
layout.show(2)

m <- matrix(0:3, 2, 2)
layout(m, widths=c(1,3), heights=c(1,3))
layout.show(3)


x <- pmin(3, pmax(-3, rnorm(50))) 
y <- pmin(3, pmax(-3, rnorm(50))) 
xhist <- hist(x, breaks=seq(-3,3,0.5), plot=FALSE) 
yhist <- hist(y, breaks=seq(-3,3,0.5), plot=FALSE) 
top <- max(c(xhist$counts, yhist$counts)) 
xrange <- c(-3,3) 
yrange <- c(-3,3) 
nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), TRUE) 
layout.show(nf) 
plot(x, y, xlim=xrange, ylim=yrange, xlab="", ylab="") 
barplot(xhist$counts, axes=FALSE, ylim=c(0, top), space=0) 
barplot(yhist$counts, axes=FALSE, xlim=c(0, top), space=0, horiz=TRUE) 


par(mfrow=c(1,1))

#############
## locator
#############

plot(cars)
locator(3,type='n')
locator(2,type='l')
text(locator(1), 'Punto', adj=0)

############
## identify
############

identify(cars$speed,cars$dist)










##############
## barchart
##############

str(barley)

?barley

barchart(yield~variety|site, data=barley, groups=year)

barchart(yield~variety|site, data=barley, groups=year, layout=c(1,6),
	ylab='Rendimiento')

barchart(yield~variety|site, data=barley, groups=year, layout=c(1,6),
	ylab='Rendimiento',scales=list(x=list(abbreviate=TRUE,minlength=5)))

barchart(yield~variety|site, data=barley, groups=year, layout=c(1,6),
	stack=TRUE, auot.key=list(points=FALSE, rectangles=TRUE, space="right"),
	ylab='Rendimiento',scales=list(x=list(rot=45)))




##############
## densityplot
##############

densityplot(~ Petal.Length, data=iris)

densityplot(~ Petal.Length | Species, data=iris)

(n <- seq(5,45,5))
(x <- rnorm(sum(n)))
(y <- factor(rep(n,n), labels=paste('n=',n)))

densityplot(~ x|y,
		panel = function(x,...)
		{
			panel.densityplot(x, col='DarkOliveGreen', ...)
			panel.mathdensity(dmath=dnorm,
						args=list(mean=mean(x), sd=sd(x)),
						col='darkblue')
		})





#############
## histogram
#############

histogram( ~ height | voice.part, data = singer)

histogram( ~ height | voice.part, data = singer, nint = 17, 
  endpoints = c(59.5, 76.5),
  layout = c(2,4), aspect = 1, xlab = "Altura (pulgadas)") 

histogram( ~ height | voice.part, data = singer, 
	xlab = "Altura (pulgadas)", type = "density", 
	panel = function(x, ...) { 
		panel.histogram(x, ...) 
		panel.mathdensity(dmath = dnorm, col = "black", 
		args = list(mean=mean(x),sd=sd(x)))
		} ) 



############
## dotplot
############

dotplot(mpg ~ disp, groups=as.factor(cyl), data=mtcars,auto.key=T)

dotplot(mpg ~ disp|as.factor(cyl), groups=am, data=mtcars,auto.key=T)

dotplot(variety ~ yield | site, groups=year, data=barley, auto.key=list(columns=2)) 




###############
## bwplot
###############

bwplot(voice.part ~ height, data=singer, xlab="Altura (pulgadas)") 

bwplot(height ~ voice.part, data=singer, ylab="Altura (pulgadas)") 

bwplot(variety ~ yield | site,  data=barley, auto.key=list(columns=2)) 

bwplot(variety ~ yield | year,  data=barley, auto.key=list(columns=2)) 



#############
## stripplot
#############


stripplot(voice.part ~ height, data = singer,
xlab = "Altura (pulgadas)")

stripplot(voice.part ~ jitter(height), data = singer,  
xlab = "Altura (pulgadas)")

stripplot(voice.part ~ jitter(height), data = singer, jitter = TRUE, 
xlab = "Altura (pulgadas)")




#############
## qqmath
#############

variables <- rexp(500, rate=0.5)
grupos <- rep(1:10,rep(50,10))
ejexp <- data.frame(cbind(variables,grupos))

qqmath(~ejexp[,1],distribution=qexp,xlab='Dist. Exp.',ylab='Muestra')

qqmath(~ejexp[,1] | as.factor(ejexp[,2]), 
   distribution=qexp,xlab='Dist. Exp.',ylab='Muestra')


qqmath(~ejexp[,1], distribution=qexp, xlab='Dist. Exp.',ylab='Muestra',
	prepanel=prepanel.qqmathline,
	panel=function(x,...){
		panel.qqmathline(x,...)
		panel.qqmath(x,...)})

qqmath(~ejexp[,1] | as.factor(ejexp[,2]), distribution=qexp,
	xlab='Dist. Exp.',ylab='Muestra',
	prepanel=prepanel.qqmathline,
	panel=function(x,...){
		panel.qqmathline(x,...)
		panel.qqmath(x,...)})



###############
## Graficos Bivariados
###############

############
## xyplot
############

xyplot(Petal.Width ~ Petal.Length, data = iris, groups=Species, auto.key=T)

xyplot(Petal.Width ~ Petal.Length | Species, data = iris, groups=Species, auto.key=T)

xyplot(Petal.Width ~ Petal.Length, data = iris, groups=Species, 
panel = panel.superpose, type=c('p','smooth'), span=.75,
auto.key=list(x=0.15, y=0.85))


################
## levelplot
################

 x <- seq(pi/4, 5 * pi, length = 100) 
 y <- seq(pi/4, 5 * pi, length = 100) 
 r <- as.vector(sqrt(outer(x^2, y^2, "+"))) 
 grid <- expand.grid(x=x, y=y) 
 grid$z <- cos(r^2) * exp(-r/(pi^3)) 
 levelplot(z~x*y, grid, cuts = 50, scales=list(log="e"), 
   xlab="", ylab="", main="Funcion Extraña", sub="con escalas logaritmicas", 
   region = TRUE) 



################
## contourplot
################



contourplot(volcano, at=seq(floor(min(volcano)/10)*10,ceiling(max(volcano)/10)*10, by=10),
 main='Curvas de Nivel, Volcan Maunga Whau, Auckland',
 sub='Intervalo entre curvas 10 m.', region=T,
 col.regions=terrain.colors(100))



################
## cloud
################

help(cloud)

cloud(Sepal.Length ~ Petal.Length * Petal.Width, groups=Species,data=iris)
cloud(Sepal.Length ~ Petal.Length * Petal.Width, groups=Species,data=iris,
 screen = list(x = -90, y = 70))
cloud(Sepal.Length ~ Petal.Length * Petal.Width, groups=Species,data=iris,
 screen = list(x = -90, y = 70), distance = .4, zoom = .6)
cloud(Sepal.Length ~ Petal.Length * Petal.Width|Species,data=iris,
 screen = list(x = -90, y = 70), distance = .4, zoom = .6)

###########
## Otro ejemplo
###########
par.set <- list(axis.line = list(col = "transparent"), clip = list(panel = FALSE)) 
print(cloud(Sepal.Length ~ Petal.Length * Petal.Width, data = iris, cex = .8, groups = Species, 
main = "Stereo", screen = list(z = 20, x = -70, y = 3), par.settings = par.set), split = c(1,1,2,1), 
more = TRUE) 
print(cloud(Sepal.Length ~ Petal.Length * Petal.Width, data = iris, cex = .8, groups = Species, 
main = "Stereo", screen = list(z = 20, x = -70, y = 0), par.settings = par.set), split = c(2,1,2,1)) 


##############
## wireframe
##############

wireframe(volcano, shade = TRUE, aspect = c(61/87, 0.4), light.source = c(10,0,10)) 

g <- expand.grid(x = 1:10, y = 5:15, gr = 1:2) 
g$z <- log((g$x^g$gr + g$y^2) * g$gr) 

wireframe(z ~ x * y, data = g, groups = gr, scales = list(arrows = FALSE), drape = TRUE, colorkey = TRUE, screen = list(z = 30, x = -60)) 



##############
## splom
##############

splom(~iris[1:4], groups=Species, data=iris, xlab='', panel= panel.superpose,
auto.key=list(columns=3))

splom(~iris[1:3] | Species, data=iris, pscales=0,
 varnames = c('Sepal\nLength', 'Sepal\nWidth', 'Petal\nLength'))


splom(~iris[1:3] | Species, data=iris,layout=c(2,2), pscales=0,
 varnames = c('Sepal\nLength', 'Sepal\nWidth', 'Petal\nLength'),
 page=function(...){ltext(x=seq(.65,.8,len=4), y=seq(.9,.6,len=4),
 lab=c('Tres','Variedades','de','Iris'), cex=2)})



##############
## parallel
##############

parallel(~iris[,1:4] | Species, data=iris, layout=c(3,1))



########################
## Programacion
########################


round(12.345)
round(12.345,2)
round(123456,-3)

trunc(12.345)
floor(12.345)
ceiling(12.345)
trunc(-12.345)
floor(-12.345)
ceiling(-12.345)


5 %/% 2
5%%2

x <- 1:10
x[x%%3==0]


#############
## subset, transform, split
#############

iris.setosa <- subset(iris, Species=='setosa')
iris.setosa <- transform(iris.setosa,PLC = (Petal.Length-mean(Petal.Length)))

split(iris$Sepal.Length,iris$Species)
iris.lista <- split(iris[,1:4],iris$Species)



x <- 1:6

x > 2 & x <= 4
x > 2 | x <= 4
x <= 2 | x > 4
xor(x > 2 , x <= 4)
xor(x <= 2 , x > 4)
! x<2
	

y <- c(NA, TRUE, FALSE)
names(y) <- as.character(y)
outer(y,y,'&')
outer(y,y,'|')
outer(y,y,'xor')

355/113
all.equal(pi,355/113)
all.equal(pi,355/113,tolerance=0.0001)


############
## Datos Faltantes
############

(aa <- c(1:3, ,9))
(aa <- c(1:3,NA,9))
sum(aa)
max(aa)
2*aa

aa == NA

aa>2
aa[aa>2]

is.na(aa)
aa[is.na(aa)]
aa[!is.na(aa)]

(bb <- 1:9)
is.na(bb)[6] <- T
bb 

0/0
1/0 + log(0)
is.na(0/0)

(cc <- c(1, 1/0, 0/0, NA))
is.na(cc)
is.finite(cc)
is.infinite(cc)
is.nan(cc)

################################
## Manejo de Caracteres
################################


(tt <- c('esta es una prueba', 'otra', 'y otra mas'))
nchar(tt)


paste(c('Altura','Peso'), rep(c(1,2),c(2,2)))
paste(c('X','Y'),1:4, sep='')
paste(c('X','Y'),1:4, sep='',collapse='+')

##########################
## Scripts
##########################

> a1 <- rexp(100) # Simulamos 100 exponenciales
> a2 <- rexp(100) # Simulamos 100 exponenciales
b <- rnorm(100) # Simulamos 100 normales
x1 <- a1 + b
x2 <- a2 + b
r <- cor(x1,x2)
print(r)














############
### Para ver los simbolos disponibles
############
Pex <- 3 ## good for both .Device=="postscript" and "x11"
ipch <- 0:35; np <- length(ipch); k <- floor(sqrt(np)); dd <- c(-1,1)/2
rx <- dd + range(ix <- ipch %/% k)
ry <- dd + range(iy <- 3 + (k-1)- ipch %% k)
pch <- as.list(ipch)
pch[26+ 1:10] <- as.list(c("*",".", "o","O","0","+","-","|","%","#"))
plot(rx, ry, type="n", axes = FALSE, xlab = "", ylab = "",
     main = paste("plot symbols :  points (...  pch = *, cex =", Pex,")"))
abline(v = ix, h = iy, col = "lightgray", lty = "dotted")
for(i in 1:np) {
  pc <- pch[[i]]
  points(ix[i], iy[i], pch = pc, col = "red", bg = "yellow", cex = Pex)
  ## red symbols with a yellow interior (where available)
  text(ix[i] - .3, iy[i], pc, col = "brown", cex = 1.2)
}











