====== Francisco ====== {{:bie5782:01_curso_atual:alunos:trabalho_final:francisco:2.jpg?200|}} Doutorando Depto. de Zoologia, IBUSP [[.:exec]] ====== Trabalho Final ====== ===== Proposta A ===== O trabalho de campo do meu doutorado consiste na execução de transecções nas quais faço amostragem de aves de rapina diurnas e urubus. Para a análise exploratória dos dados coletados são úteis gráficos que ilustram a quantidade de detecções (barras) e #detecções/km (linha) por transecção para cada espécie. Minha proposta é elaborar uma função que organize os dados das planilhas de detecção de cada transecção em um único arquivo/objeto e, principalmente, construa diretamente tais gráficos para a análise exploratória. ===== Comentários ===== Tá super factivel, mas acho que talvez um pouco simples. Não sei como poderia ir além disso, mas talvez já fosse possível calcular abundancias a partir desses dados organizados? O pacote "vegan" tem várias funções que poderiam ser usadas para rechear a função de forma bem interessante. --- //[[macfabio@gmail.com|Fabio de A. Machado]] 2011/04/06 18:12// ==== Proposta B ==== Outro dado coletado nos meus trabalhos de campo é a distância perpendicular de cada registro à linha de transecção. Essas distâncias são medidas com o auxílio de telêmetro. No entanto, é possível que opte por tranformá-las em classes de distância (ex. 0-10 metros, 10-20, 20-30, etc.) A proposta B consiste então na elaboração de uma função que rapidamente faça a conversão dessas medidas para todo um conjunto de dados. ==== Comentários ==== Isso não poderia já ser incluida na proposta A? --- //[[macfabio@gmail.com|Fabio de A. Machado]] 2011/04/06 18:18// ==== COmentário ALe ==== COncordo plenamente com o Fabio, ficaria muito legal se implementasse as duas coisas em uma única função. --- //[[adalardo@usp.br|Alexandre Adalardo de Oliveira]] 2011/04/06 19:07// ==== Comentários Paulo ==== O plano B é resolvido com um único comando, com a função ''cut''. Além disto, está em parecendo muito específica. Vc consegue generalizar para uso de pessoas que façam censo por transecções, mesmo que seja uma sequência de cálculos simples? ===== Função ===== ===Comentários finais - Francisco=== Seguindo a sugestão do Paulo optei por, ao invéz de incluir o plano B na função, gerar dados generalizados, e eu pensei que seria útil que a função gerasse uma tabela com sumário de abundância por espécie e transecto, para avaliação com os gráficos. A função final trabalha com qualquer número de espécies e transectos na planilha. Nos exemplos do help da função criei data.frames hipotéticos para a execução da função sob diferentes condições. ===Código da Função=== transect.analysis=function(x,y=TRUE,z=FALSE)###Arguments: x=data.frame; y=logic, if TRUE plot will be created in a single graphic window, otherwise each on its own window; z=logic, controls return of summary data.frame. { somaspp=aggregate(x$quantity,by=list(x$species),FUN=sum)##creates a data.frame with sum of records for each species. sppdez=subset(somaspp,somaspp$x>10)## creates a subset of the data.frame above with species with >10 records. listasppdez=unique(sppdez$Group.1)##creates a vector with the names of species in the subset. contesp=length(listasppdez)#counts the number of species with >10 records ntrans=unique(x$transect) ntrans2=length(ntrans) ntrans3=ntrans[-ntrans2] if (y==TRUE&contesp>=15) { cat("The number of species in the sample is too large for 1 graphic window displaying")##sets warning message when number of y=TRUE and number of plots>15 } if (y==TRUE&contesp<=15) { quartz("Exploratory Graphs", 11,6) ##open new graphic window for up to 15 histograms mat=matrix(c(1:15),3,5, byrow=T) layout(mat,widths=c(1,1,1,1,1),heights=c(1,1,1)) layout.show(15) } for(i in listasppdez) #start computing histogram data for each species { if (y==FALSE|y==TRUE&contesp>=15) { quartz( "Exploratory Graph") #sets new graphic window for each species } tab1=subset(x,x$species==i)#selects a subset by species. tab1$transect=as.numeric(tab1$transect)#transforms "transect" factor into numeric for calculation of frequency. hist(tab1$transect,main=i,breaks=seq(-0.5,(ntrans2+2),1) ,ylab="Detections",xlab="Transects", xaxt="n") ##plots histogram without x axis axis(1,at=c(ntrans),labels=c(ntrans),pos=0,) ##includes new x axis with ticks correcty placed. par.hist=hist(tab1$transect,breaks=seq(-0.5,(ntrans2+2),1) ,plot=F)###creates an object with values of histogream frequencies. counts=as.numeric(par.hist$counts)###vector with counts for each transect. tlength=c(1,unique(x$transect.length),1)#creates a vector with length of each transect plus two values at the extremities for alignment with vector "counts". tlength2=counts/tlength##creates a vector with frequency/distance ratio for each transect. tlength3=tlength2[-c(1,(ntrans2+2))]###removes first and last values of above vector. ntrans3=as.numeric(ntrans[-ntrans2]) for (t in ntrans3) ##plots segments for each transect { tlength4=tlength3*50 k=t+1 segments(t,(tlength4[t]),(k),(tlength4[k]), col="firebrick") } axis(4, at=c(round(tlength3*50),2), lwd.ticks=0, col="firebrick", col.axis="firebrick") if (y==TRUE) ##fits label size to type of graphic window created { mtext("Detections/Km",side=4, col="firebrick",cex=0.6) } else { mtext("Detections/Km",side=4, col="firebrick",cex=1) } } if (z==TRUE) {resultado=aggregate(x$quantity,by=list(x$species, x$transect),FUN=sum) colnames(resultado)=c("Species","Transect","Detections") return(resultado) } } ===Arquivo da Função=== {{:bie5782:01_curso_atual:alunos:trabalho_final:francisco:transect_analysis.r|}} ===Arquivo do Help=== transect.analysis R Documentation Exploratory Graphical Analysis of Abundance Data from Transect Sampling Description Get summarized histograms of abundance of species per transect surveyed with Detections/Km line from data.frame of individual detections. Usage transect.analysis(x, y = TRUE, z = FALSE) Arguments x data.frame with individual detections: must have specific names for columns (see Details). y logical expression indicating wether histograms (up to 15) will be placed within one graphical window or on individual windows. z logical; should the function return a summarized table with #detections/species/transect? Details This function requires input data.frame (x) with individual detections (which may have more than one individual) as rows and columns with: species denomination; # of individuals per detection; denomination of transect surveyed; and length of transect (Km) data. These columns must be denominated, respectively, as: "species", "quantity", "transect" and "transect.length". Other columns in the data.frame will be ignored. The function returns n histograms, where n is the number of species with ten or more individuals detected among all transects. Each histogram shows the number of individuals per transect, and a line corresponding to the number of detections/Km ratio per transect. y argument indicates wether histograms will be plotted within one graphical window (the default, y = TRUE) or on individual windows (y = FALSE). When y = TRUE, the maximum number of histograms plotted (= n) is 15. If y=TRUE and n > 15, the function will run as if y= FALSE and a warning will be given. Value comp1: n objects of class "histogram", with additional components "axis" and "segments". comp2: if z=TRUE, the result of function aggregate(x$quantity,by=list(x$species, x$transect),FUN=sum). Author Francisco Voeroes Dénes See Also histogram, data.frame. Examples: ###ex1. Analysis of a five transect data set with five species and 50 random detections. Note that # of individuals detected is > than # of detections. Since here y = TRUE (default) and n <15, all plots will be created in a single graphic window.z=TRUE sets function to return a summary as a data frame of detections per species and transects. species <- sample(c("Falco sparverius", "Buteo brachyurus","Falco femoralis", "Cathartes aura", "Coragyps atratus"), 50, replace=TRUE)##vector with species names quantity <- rpois(50,3)##number of individuals for each detection transect <- c(rep(1,10), rep(2,10), rep(3,10),rep(4,10), rep(5,10))## transect where detection took place transect.length <- c(rep(100,10),rep(120,10),rep(170,10),rep(90,10),rep(200,10)) ##length of respective transect raptors1 <- data.frame(species,quantity, transect, transect.length)##coerce vectors into data.frame transect.analysis(raptors1,z=TRUE) ##ex2. Analysis of a five transect data set with 17 species and 100 random detections. Here, y = TRUE (default) and n>15, so function runs as if y=FALSE and a warning is given. species2 <- sample(LETTERS[1:17], 100, replace=TRUE)##vector with species names as uppercase letters quantity <- rpois(100,11)##number of individuals for each detection transect <- c(rep(1,20), rep(2,20), rep(3,10),rep(4,30), rep(5,20))## transect where detection took place transect.length <- c(rep(100,20),rep(120,20),rep(170,10),rep(90,30),rep(200,20)) ##length of respective transect raptors2 <- data.frame(species2,quantity, transect, transect.length)##coerce vectors into data.frame transect.analysis(raptors2)