Archive for the ‘Uncategorized’ Category

R studio, una nueva interfaz de trabajo en R.

Tuesday, November 15th, 2011

Hay varias herramientas para trabajar con R, editores como TinnR, StatET, Emacs, Vim, Notepad++, NppToR, etc., RStudio ™ es ​​un nuevo entorno de desarrollo integrado de R. RStudio combina una interfaz de usuario intuitiva R con un editor de R. A pesar de estar en una version 0.94, permite editar y llevar un seguimiento de todos los datos (bases, resultados) y los graficos realizados. Además ayuda a completar el codigo. También hay un libro que describe su uso y configuración. Por otro lado la posibilidad de uso en multiplataforma (Windows, linux, MacOS y soporte WEB) va a hacer que RStudio se convierta pronto en una de las herramientas más usadas de R.

Hay herramientas interesantes no incluidas en la instalación RStudio, como un paquete de R “manipulate”, que van a permitir, metiendo un poco de código, la modificación de los ejes, colores objetos, etc.

Fuente RStudio

Ideas for cooking ggplot2

Thursday, January 20th, 2011

Ideas para ggplot2

#####
library(ggplot2)
 
data = structure(list(Trt = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("A",
"B"), class = "factor"), Clone = structure(c(1L, 2L,
3L, 4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L), .Label =
c("1",
"2", "3", "4", "5", "6", "7", "8",
"Mean"), class = "factor"), x = c(-27.5996, -27.5333, -27.0267,
-27.6467, -26.7667, -28.07, -27.4608, -28.1867, -29.3833, -28.2196,
-29.6567, -28.9608, -29.6167, -30.1892, -28.5633, -30.2208),
    x.SE = c(0.3603, 0.3085, 0.3085, 0.3085, 0.3085, 0.3085,
    0.4831, 0.3085, 0.3085, 0.3601, 0.3085, 0.3603, 0.3085, 0.2402,
    0.3085, 0.3686), y = c(98.12, 69.84, 78.47, 68.03, 58.2,
    33.39, 46.57, 65.75, 40.01, 38.23, 34.09, 44.37, 31.92, 39.85,
    34.37, 41.27), y.SE = c(15.32, 12.51, 12.51, 12.51, 12.51,
    12.51, 15.32, 12.51, 12.51, 15.32, 12.51, 15.32, 12.51, 12.51,
    12.51, 15.32)), .Names = c("Trt", "Clone", "x", "x.SE",
"y", "y.SE"), class = "data.frame", row.names = 3:18)
 
# x and ylim for geom_errorbar with standard error
fig.xlim = aes(xmin = x - x.SE, xmax = x + x.SE, height=0)
fig.ylim = aes(ymin=y-y.SE, ymax=y+y.SE, height=0)
 
fig1 = ggplot(data, aes(x, y, shape=factor(Trt), fill=factor(Clone),
size=factor(Clone)) ) +
scale_shape_manual(values=c(23,21), "Treatment") +
scale_fill_brewer(palette="Set1", "Clone") +
theme_bw() +
coord_cartesian(xlim= c(-31,-26), ylim=c(0,120) ) +
scale_y_continuous(limits=c(0,120)) +
scale_x_continuous(limits=c(-31,-26)) +
geom_errorbar(fig.ylim, width=0, size=0.3,colour="black") +
geom_errorbarh(fig.xlim, size=0.3, colour="black") +
geom_point(aes(size=factor(Clone))) +
scale_size_manual(values=c(2,2,4,2,4,4,2,2), "Clone") +
opts(panel.grid.minor=theme_line(colour = NA, size = 0.0),
panel.grid.major=theme_line(colour = NA, size = 0.0),
strip.background = theme_rect(col="black",fill=NA))
fig1

############################ In Grey scale
 
fig2 = ggplot(data, aes(x, y, shape=factor(Trt))) +
scale_shape_manual(values=c(23,21), "Treatment") +
theme_bw() +
coord_cartesian(xlim= c(-31,-26), ylim=c(0,120) ) +
scale_y_continuous(limits=c(0,120)) +
scale_x_continuous(limits=c(-31,-26)) +
geom_errorbar(fig.ylim, width=0, size=0.3,colour="black") +
geom_errorbarh(fig.xlim, size=0.3, colour="black") +
geom_point(size=6, fill="white") +
geom_text(aes(label=Clone),size=4) +
opts(panel.grid.minor=theme_line(colour = NA, size = 0.0),
panel.grid.major=theme_line(colour = NA, size = 0.0),
strip.background = theme_rect(col="black",fill=NA))
 
fig2

#################Grey scale2 y conservar  grid lines
 
fig3 = ggplot(data, aes(x, y, shape=factor(Trt), colour = factor(Trt))) +
  geom_errorbar(fig.ylim, width=0, size=0.3) +
  geom_errorbarh(fig.xlim, size=0.3) +
  geom_point(size=6, fill="white") +
  geom_text(aes(label=Clone),size=3, colour = "grey50") +
  scale_shape_manual(values=c(23,21), "Treatment") +
  scale_colour_grey("Treatment", end = 0.6) +
  theme_bw() 
fig3

Fuente: Ideas for converting a colour to a gray graph

Ggplot2 graficas de barras de error

Thursday, January 13th, 2011

Empezar con ggplot2….

 
#introducir tabla de datos 
 
 
   z<- structure(list(Intermoult = structure (c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 5L, 6L, 7L,
8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L),.Label = c("Instar1","Instar2","Instar3 ","Instar4","Instar5 ","Instar6","Instar7","Instar8",
"Instar9","Instar10","Instar11","Instar12","Instar13","Instar14" ,"Instar15 ","Instar16"),class = "factor"), 
Way = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L , 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), 
.Label = c(" Initial 200 larvae", " 80 larvae transferred from the mass culture"), class = "factor"),
Mean = c(8.4,7.6,9.4,11.3,16.7,10.3,17.3,14.2,13.4,14.4,14.2,16.4,19.0,22.3,27.0,NA,16.7,17.0,18.3,15.0,15.6,15.1,14.7,17.6,21.1,18.8,27.0),
SD = c(0.5,1.3,1.0,1.6,2.4,1.7,4.0,3.5,2.1,4.1,2.5,2.2,3.5,3.9,0.0,NA,5.0,6.7,5.8,4.7,4.0,2.6,2.1,3.2,4.5,1.3,0.0),
upp = c(11,19,13,15,20,15,22,22,17,25,19,20,25,28,27,NA,24,33,30,28,26,20,19,23,30,20,27),
low = c(8,6,8,9,13,9,12,10,11,12,10,13,14,19,27,NA,12,10,11,8,11,11,11,13,16,17,27)) ,
class = "data.frame",  ,row.names = c(NA, -27L) )
colnames(z)<- c("Intermoult", "Way", "Mean", "SD", "upper", "lower")
 
###Crear plot
 
library(ggplot2)
 
pdf(file = "intermuda2.pdf", width = 6, height = 6, dpi= 600)    #Guardarlo como pdf
 
 
 
p<-ggplot(z,aes(x=Intermoult,y=Mean,ymin=Mean-SD,ymax=Mean+SD,
             groups=Way,colour=Way))+  
  geom_point(position=position_dodge(width=0.5))+ 
  geom_pointrange(width=0.5,position=position_dodge(width=0.5))+
   labs(x="Intermoult",y="Intermoult Period (Days)")+ theme_bw()+ opts(legend.position = c(0.18,0.6))+ #colocar la leyenda 
 scale_colour_manual("", c(" Initial 200 larvae" = "#5CB0E2", " 80 larvae transferred from the mass culture" = "darkblue"))
 
   p + ylim(c(-1, 30))
 
 
 
 
 #Características del plot#########################
 
last_plot() + opts(panel.grid.minor = theme_line(colour = NA),
panel.grid.major = theme_line(colour = NA),
plot.background =  theme_rect(colour = NA, fill = NA),
axis.title.x = theme_text( face = "bold"),
axis.title.y = theme_text( face = "bold", angle = 90),
legend.key = theme_rect ( colour = NA, fill = NA))
 
 
dev.off
 
#colocar graficos en una página (creamos un nuevo grid y seleccionamos la forma)
library(gridExtra)
grid.newpage()
print(grid.arrange(plot1, plot2, plot3,plot4, plot5, nrow=1, ncol=5))   #ponerlos en columnas y filas

Link plots sobre áreas geográficas

Friday, December 10th, 2010

Aquí un link con código para hacer diversos plots de datos en áreas

Lorenz curves and Gini index

Wednesday, May 26th, 2010

La Lorenz curve y el Gini Index se usan mucho como indicadores de la concentración de la riqueza (miden el grado de concentración de la renta en un país). En la literatura pesquera ha sido utilizada unas pocas veces para ilustrar la concentración de la abundancia. Nosotros queremos utilizarlos para analizar la concentración del esfuerzo de pesca, lo que en principio no se ha hecho antes.

#PARA HACER CURVAS DE LORENZ E INDICES GINI:
#1. Hace falta tener cargado el package "ineq"
library(ineq)
Lorenz <- read.table(file = "C:\\R.gps\\Lorenz.txt",header = TRUE)
names(Lorenz)
summary(Lorenz)
 
#Loop que hizo Inés para hacer las curvas y estimar los indices de las 31 patches de erizo
#y guardar los primeros en un pdf (sin el loop tendría que hacer un código para cada uno de los 31 patches):
giniIndex <- NULL
pdf("GraficosLorentz.pdf", width=11.69, height=8.26)
op <- par(mfrow=c(3,7))
for(i in 1:31){
Mtemp <-  subset(Lorenz,Mancha==as.character(i), select=4)#Columna4=n.celda
plot(Lc(Mtemp[,1]), main=paste("Mancha", i, sep=" "))
giniIndex[i] <- ineq(Mtemp[,1])
}
par(op)
dev.off()
 
#Para guardar los índices:
write(giniIndex,file="clipboard",ncolumns=1)
#o
write.csv(giniIndex,file="ginis.csv")
#Resultó mejor la 2º pq da los datos en una unica columna con el nº 
#de patch asociado
 
##FIGURA DE LOS 3 PATCHES MÁS VISITADOS (7,15Y22):
 
M7<-subset(Lorenz,Mancha=="7")
M15<-subset(Lorenz,Mancha=="15")
M22<-subset(Lorenz,Mancha=="22")
Lc.7<-Lc(M7$n.celda)
Lc.15<-Lc(M15$n.celda)
Lc.22<-Lc(M22$n.celda)
plot(Lc.7,ylab="",xlab="",main="")
lines(Lc.15,lty="dashed")
lines(Lc.22,lty="dotted")

Predictions and/or confidence (or prediction) intervals on predictions

Tuesday, May 25th, 2010

Los intervalos de confianza de la funcion predict nos han dado muchos quebraderos de cabeza!
El codigo calcula los intervalos de confianza de los fitted values de los predict !!

library(nlme) 
fm1 <- lme(distance ~ age*Sex, random = ~ 1 + age | Subject, data = Orthodont) 
 
plot(Orthodont)
newdat <- expand.grid(age=c(8,10,12,14), Sex=c("Male","Female")) 
 
newdat$pred <- predict(fm1, newdat, level = 0)
 
Designmat <- model.matrix(eval(eval(fm1$call$fixed)[-2]), newdat[-3]) 
predvar <- diag(Designmat %*% fm1$varFix %*% t(Designmat)) 
newdat$SE <- sqrt(predvar) 
 
newdat$SE2 <- sqrt(predvar+fm1$sigma^2)
 
library(ggplot2) 
pd <- position_dodge(width=0.4) 
ggplot(newdat,aes(x=age,y=pred,colour=Sex))+ 
   geom_point(position=pd)+ 
  geom_linerange(aes(ymin=pred-2*SE,ymax=pred+2*SE), position=pd)
 
 
## prediction intervals 
ggplot(newdat,aes(x=age,y=pred,colour=Sex))+ 
   geom_point(position=pd)+ 
   geom_linerange(aes(ymin=pred-2*SE2,ymax=pred+2*SE2), position=pd)

Fuente: Wikidot