Anda di halaman 1dari 12

####################### Clase 1 ###########################

######################INTRODUCCIN AL R####################
###1. Utilizando ayuda en R
help(solve)
?read.table
help.search("data input")
help.start()
find("lowess")
apropos("lm")
4;m=5
###2. Utilizando librerias
library(sn)
library(help=sn)
install.packages("akima")
install.packages("chron")
install.packages("lme4")
install.packages("mcmc")
install.packages("odesolve")
install.packages("spdep")
install.packages("spatstat")
install.packages("tree")
###3. Editando datos
library(MASS)
attach(bacteria)
fix(bacteria)
#### Importante: para guardar las salidas en un archivo
y no mostrarlo en la consola utilizar
sink("salida.lis")
Para desactivar la opcin
sink()
###4. Objetos y librerias
#####Saber que hay en R
objects()
search()
#####Eliminar todo de la memoria

detach(bacteria)
rm(list=ls())
###5. Funciones matemticas
round(9.7222222,digits=3)
cos(9.772)
abs(-4.566)
###6. Infinitos y otras cosas raras
3/0
Inf/-Inf
is.finite(10)
is.infinite(10)
is.infinite(Inf)
##### Manejo de valores perdidos
x=c(1:8,NA)
mean(x)
mean(x,na.rm=T)
vmv=c(1:6,NA,NA,9:12)
which(is.na(vmv))
vmv[is.na(vmv)]=0
vmv
###Setting directory
mywork<-"/users/mauricio/documents/udec/aed/clases/clase 01-02"
setwd(mywork)
###################NUMEROS Y VECTORES#######################
####1. Operaciones con nmeros
7*3
7+2*3
(7+2)*3
12/2+4
12/(2+4)
3^2
2*3^2

####2. Almacenamiento de nmeros


x=2
print(x)
x
####3. Creacin de vectores
y=c(1,2,3,4,5,6,7,8,9,10)
y=scan()
datos=read.table("datos.txt")
y=datos$V1
####2. Operaciones con vectores
length(y)
x=c(11:20)
z=x*y
z=x+y
x^2
w=c(x,y,999)
t=c("A","B","C")
####3. Creacin de secuencias
q=seq(2,100,2)
r=rep(5,10)
####4. Etiquetado
y=c(25,12,7,4,6,2,1,0,2)
names(y)=c("Estado 0","Estado 1","Estado 2",
"Estado 3","Estado 4","Estado 5","Estado 6",
"Estado 7","Estado 8")
y=as.vector(y)
####5. Funciones de vectores
y=1:10
range(y)
mean(y)
median(y)

sort(y)
sort(y,decreasing=TRUE)
rank(y)
quantile(y)
cumsum(y)
cumprod(y)
data=c(7,4,6,8,9,1,0,3,2,5,0)
ranking=rank(data)
sorteado=sort(data)
ordenado=order(data)
view=data.frame(data,ranking,sorteado,ordenado)
view
### Importante, el comando rev(order) hace el orden al reves.
ordenado2<-rev(order(data))
view<-data.frame(data,ranking,sorteado,ordenado,ordenado2)
view
##### Clculo de varianza!!
x=c(7,5,7,2,4,6,1,6,2,3,7,5,7,2,4,6,1,6,2,3)
length(x)
sum((x-mean(x))^2)/(length(x)-1)
var(x)
####6. Funcin TAPPLY
data<-read.table("Desktop//daphnia.txt",header=T)
attach(data)
names(data)
data
tapply(Growth.rate,Detergent,mean)
tapply(Growth.rate,list(Water,Daphnia),median)
tapply(Growth.rate,list(Water,Daphnia,Detergent),median)
#### Otras estadsticas descriptivas!!!
tapply(Growth.rate,list(Water,Daphnia),mean)
tapply(Growth.rate,list(Water,Daphnia),median)
tapply(Growth.rate,list(Water,Daphnia),var)

tapply(Growth.rate,list(Water,Daphnia),sd)
##### Clculo de la mediana!!
y=sort(x)
aux=rep(1,length(y))
freq.abs=tapply(aux,list(y),sum)
cumsum(freq.abs)/sum(freq.abs)
####7. Comando WITH
with(OrchardSprays,boxplot(decrease~treatment))
library(MASS)
with(bacteria,tapply((y=="n"),trt,sum))
with(mammals,plot(body,brain,log="xy"))
reg.data<-read.table("Desktop//regression.txt",header=T)
with(reg.data,lm(growth~tannin))
with(reg.data,summary(lm(growth~tannin)))
####8. Trabajando con sub-vectores
##### Doble uso de sum
x=0:10
sum(x)
sum(x<5)
sum(x[x<5])
x<5
1*(x<5)
##### Comando which
y=c(8,3,5,7,6,6,8,9,2,3,9,4,10,4,11)
which(y>5)
y[which(y>5)]
y[y>5]
length(y)
length(y[y>5])
##### Extraccin de muestras
xv<-rnorm(100,100,10)

xv[seq(1,length(xv),5)]
Location[order(Price)]
####9. Funcin sample
y=c(8,3,5,7,6,6,8,9,2,3,9,4,10,4,11)
sample(y)
sample(y)
sample(y,5)
sample(y,replace=T)
p=c(1,2,3,4,5,5,4,3,2,1)
x=1:10
sample(x,5,prob=p)
####################ARREGLOS Y MATRICES####################
###1. Matrices
#####1.1 Defincin de matrices
X=matrix(c(1,0,0,0,1,0,0,0,1),ncol=3,nrow=3)
class(X)
attributes(X)
vector=c(1,2,3,4,4,3,2,1)
V=matrix(vector,byrow=F,nrow=2)
V
vector=c(1,2,3,4,4,3,2,1)
V=matrix(vector,byrow=T,nrow=2)
V
vector=c(1,2,3,4,4,3,2,1)
dim(vector)=c(4,2)
vector
#####1.2 Etiquetado de filas y columnas
X=matrix(rnorm(20,75,5),ncol=5,nrow=4)
X
etiq.col=c("Sujeto 1","Sujeto 2","Sujeto 3","Sujeto 4","Sujeto 5")
etiq.fil=c("Tiempo 1","Tiempo 2","Tiempo 3","Tiempo 4")
colnames(X)=etiq.col
rownames(X)=etiq.fil
X
dimnames(X)=list(NULL,etiq.col)
X

#####1.3 Operaciones con filas y columnas


X=matrix(rpois(20,2),nrow=4,ncol=5)
mean(X[,5])
var(X[,5])
rowSums(X)
colSums(X)
rowMeans(X)
colMeans(X)
#####1.4 Comando apply y lapply
X=matrix(1:24,nrow=4)
X
apply(X,1,sum)
apply(X,2,sum)
apply(X,2,sqrt)
sqrt(X)
apply(X,2,function(x) x^2+x)
######Creacin de factores
dolor=c(0,3,2,2,1)
fdolor=factor(dolor,level=0:3)
levels(fdolor)=c("Ninguno","Leve","Medio","Severo")
fdolor
as.numeric(fdolor)
levels(fdolor)
texto.dolor=c("Ninguno","Leve","Medio","Medio","Severo")
factor(texto.dolor)
######Creacin de listas
x =list(a = 1:10, beta = exp(-3:3), logic = c(TRUE,FALSE,FALSE,TRUE))
x$a
x$beta
x$logic
lapply(x,mean)
lapply(x, quantile, probs = 1:3/4)
lapply(x,class)
#####1.5 Adicin de filas y columnas
X=cbind(X,apply(X,1,mean))
colnames(X)=c(1:6,"Media")

#####1.6 Comando Sweep


matdata=read.table("Desktop//sweepdata.txt")
matdata
cols=apply(matdata,2,mean)
suma=apply(matdata,2,sum)
sweep(matdata,2,cols)
sweep(matdata,2,suma)
A=array(1:24, dim = 4:2)
sweep(A, 2, 5)
sweep(A, 1, 5)
A.min =apply(A, 1, min)
sweep(A, 1, A.min)
sweep(A, 1:2, apply(A, 1:2, mean))
#####1.7 Operaciones
A=matrix(0:5, 2, 3)
B=matrix(seq(0, 10, 2), 2, 3)
A
B
A+B
A-B
t(A)%*%B
solve(A%*%t(A))
####2. Arreglos
array(1:12, c(2, 3, 2))
A=letters[1:24]
dim(A)=c(4,2,3)
A[2,,]
A[,2,]
A[,,2]
####3. Data frames
A.frame=data.frame(A)
attach(A.frame)
X1
##### 3.1 Seleccin condicional y transformaciones

intake.pre=c(5260,5470,5640,6180,6390,6515,6805,7515,7515,8230,8770)
intake.post=c(3910,4220,3885,5160,5645,4680,5265,5975,6790,6900,7335)
d=data.frame(intake.pre,intake.post)
d$intake.pre
d[5,1]
d[5,]
d[d$intake.pre>7000,]
sel=d$intake.pre>7000
d[sel,]
d2=subset(d,sel)
d2
d3=transform(d,log.intake.pre=log(intake.pre))
d3
install.packages("ISwR")
library(ISwR)
data(energy)
energy
exp.lean=energy$expend[energy$stature=="lean"]
exp.obese=energy$expend[energy$stature=="obese"]
l=split(energy$expend,energy$stature)
####4. Uso del IF
f1=function(y){
if(y<0){z=-1}
else(z=1)
return(z)
}
f1(0)
f2=function(y){
if(y<0){z=-1}
if(y==0){z=0}
if(y>0){z=1}
return(z)
}
f2(-10)

####5. Ciclos y repeticiones


#####5.1 Uso de FOR
cuadrados=function(n){
for (i in 1:n){
print(i^2)
}
}
cuadrados(100)
calculo=function(n){
j=0
k=0
for (i in 1:n) {
j=j+1
k=k+i*j
print(i+j+k)
}
}
calculo(10)
#####5.2 Uso de REPEAT
first.success.repeat=function(p){
k=0;
repeat{
t=rbinom(1,1,p)
if(t==0){k=k+1}
else{break}
}
return(k)
}
first.success.repeat(0.1)
#####5.3 Uso de WHILE
first.success.while=function(p){
k=0;
success=FALSE
while(success == FALSE){
k=k+1
if (rbinom(1,1,p)==1){success = TRUE}
}
return(k)
}
first.success.while(0.1)
### Ejemplo Factorial de un Numero
fac=function(x){
t=1
if (x>2){
for (i in 2:x){
t=t*i
}

}
return(t)
}
fac(100)
factorial(100)
fac2=function(x){
t=1
f=x
repeat{
if (f<2){break}
else{
t=f*t
f=f-1
}
}
return(t)
}
fac3=function(x){
t=1
f=x
while(f>=2){
t=f*t
f=f-1
}
return(t)
}
fac3(100)
#####6. Funcin SWITCH
medias=function(y, media){
switch(media,
Aritmetica = mean(y),
Geometrica = exp(mean(log(y))),
Armonica = 1/mean(1/y),
Mediana = median(y),
stop("Media no incluida"))
}
medias(1:10,"Aritmetica")
medias(1:10,"Geometrica")
medias(1:10,"Armonica")
medias(1:10,"Mediana")
medias(1:10,"Trimedia")