\documentclass[a4paper, oneside, 10pt]{article} \usepackage[english]{babel} \usepackage[unicode]{hyperref} \usepackage[utf8x]{inputenc} \usepackage{listings} \usepackage{graphicx} \graphicspath{{media/}} \date{\today} \title{} \author{} \begin{document} \section{\texorpdfstring{André Francisco Bucci}{Andre Francisco Bucci}} \label{sec:andre_francisco_bucci} \includegraphics[keepaspectratio=true,width=0.8\textwidth]{bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/402816_2359329266600_1351322481_1832793_366704757_n} Mestrando em Oceanografia Biológica (Instituto Oceanográfico - IOUSP) Projeto ,,Efeitos de morfotipos de fitoplâncton no comportamento espectral da absorção da luz, e possiveis implicações para a determinação de carbono particulado por sensoriamento remoto." Desenvolvo meu projeto de mestrado no Centro de Biologia Marinha (CEBIMar-USP) sob orientação da Profa. Dra. Áurea Maria Ciotti. Basicamente, trabalho com dados bio-óticos e de contagem de fitoplâncton em microscópio provenientes de cruzeiros oceanográficos realizados na costa brasileira nos anos de 2010 e 2011. bucci.andre@usp.br \section{\texorpdfstring{Exercícios}{Exercicios}} \label{sec:exercicios} \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/exercicio01_andrebucci.r_exercicios.r}{exercicio01\_FINAL} \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/exercicio02_andrebucci.r}{exercicio02\_FINAL} \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/exercicio03_andrebucci.r}{exercicio03\_FINAL} \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/abs_costarj_dataout.txt}{abs\_costarj\_dataout.txt} \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/exercicio04_andrebucci.r}{exercicio04\_FINAL} \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/exercicio05_andrebucci.r}{exercicio05\_FINAL} \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/exercicio06_andrebucci.r}{exercicio06\_FINAL} \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/exercicio07_andrebucci.r}{exercicio07\_FINAL} \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/exercicio09_andrebucci.r}{exercicio09\_FINAL} \section{\texorpdfstring{Trabalho Final}{Trabalho Final}} \label{sec:trabalho_final} \subsection{\texorpdfstring{Plano A (Principal)}{Plano A Principal}} \label{sec:plano_a_principal} Produzir uma função que seja capaz de agrupar dados (colunas) de múltiplos arquivos proveninentes de espectrofotometros (pós-processamento) em um único dataframe e salvar esses dados em um arquivo único.\\ Especificamente:\\ 1. Todos os arquivos possuem as mesmas variáveis e exatamente na mesma ordem dentro do arquivo (sã arquivos padrões)\\ 2. Os arquivos lidos devem estar no mesmo diretório\\ 3. A rotina deverá ser rodada para cada coluna desejada (sempre será utilizada a mesma coluna para todos os arquivos)\\ 4. As colunas dos multiplos arquivos serão salvos em um dataframe e depois salvo em um arquivo (.txt de preferência) \subsection{\texorpdfstring{Plano B}{Plano B}} \label{sec:plano_b} Produzir uma função que realize a normalização de curvas de absorção de luz e plot o resultado (múltiplas curvas) em um único gráfico.\\ Especificamente:\\ 1. Cada coluna no arquivo representa os valores que irão compor a curva\\ 2. As curvas serão normalizadas (divididas) pela média dos valores de absorção em um intervalo de comprimento de onda\\ 3. Os valores resultantes serão salvos em um novo dataframe\\ 4. As novas curvas serão postadas em um único gráfico \subsection{\texorpdfstring{Comentário}{Comentario}} \label{sec:comentario} Olá André, Pode tocar a primeira proposta, mas amplie ela um pouco. Tipo, poder escolher uma única ou várias variáveis (inclusive todas) e juntando cada uma delas em arquivos diferentes, algo assim! Tente usar também funçoes interativas como choose.files() para facilitar a vida de outros usuários. --- \emph{\href{mailto:adalardo@usp.br}{Alexandre Adalardo de Oliveira} 2012/04/03 20:52} \subsection{\texorpdfstring{Função Final}{Funao Final}} \label{sec:funao_final} \subsubsection{\texorpdfstring{Com texto comentado}{Com texto comentado}} \label{sec:com_texto_comentado} \lstset{frame=single} \begin{lstlisting} agrupa.col=function(files, col, filename, wave=TRUE){ if (missing(files)){files=list.files()} else {files=files} #importando os arquivos fornecidos pela lista em "files" datalist=lapply(files,function(files){read.table(files,header=TRUE, as.is=TRUE, sep="\t", dec=".", fill=TRUE)}) #transforma a lista de arquivos importados em dataframe, dividindo-os em colunas data=data.frame(datalist); a=seq(0,length(files)); b=ncol(data.frame(datalist[1])) coluna=(a*b)+col; #seleciona todas as colunas da mesma variável de acordo com o fornecido em "col" coluna=coluna[1:(length(coluna)-1)] #remove o último elemento do vetor para que # nao seja maior que o numero maximo de colunas do dataframe inicial #seleciona os dados desejados dataout=data[coluna]; # idealmente a funcao foi criada para agrupar arquivos de espectrofotometro # da forma que idealmente, a primeira coluna deve ser os comprimento de onda # de leitura do aparelho (wave=TRUE), mas pode ser usada para qualquer tipo de arquivo # descartando a primeira coluna de comprimentos de onda (wave=FALSE) if (wave==TRUE){ wave=data[1] dataout=data.frame(wave,dataout); #os nomes das colunas do arquivo de saida sera os nomes dos arquivos da lista incial "." nome da coluna da variavel # ex. "arquivo1.coluna1", "arquivo2.coluna1", com a primeira coluna sendo o comprimento de onda que o espectrofotometro usou names(dataout)=c("wavelength",paste(files, names(data[coluna[1]]))); } else { names(dataout)=c(paste(files, names(data[coluna[1]]))); dataout=data.frame(dataout); } # cria um arquivo com as colunas desejadas write.table(dataout, file=paste(filename,".txt",sep=""), quote=FALSE, sep="\t", col.names=names(dataout),row.names=FALSE, dec=".") return(dataout) } \end{lstlisting} \subsubsection{\texorpdfstring{Sem texto comentado}{Sem texto comentado}} \label{sec:sem_texto_comentado} \lstset{frame=single} \begin{lstlisting} agrupa.col=function(files, col, filename, wave=TRUE){ if (missing(files)){files=list.files()} else {files=files} datalist=lapply(files,function(files){read.table(files,header=TRUE, as.is=TRUE, sep="\t", dec=".", fill=TRUE)}) data=data.frame(datalist); a=seq(0,length(files)); b=ncol(data.frame(datalist[1])) coluna=(a*b)+col; coluna=coluna[1:(length(coluna)-1)] dataout=data[coluna]; if (wave==TRUE){ wave=data[1] dataout=data.frame(wave,dataout); names(dataout)=c("wavelength",paste(files, names(data[coluna[1]]))); } else { names(dataout)=c(paste(files, names(data[coluna[1]]))); dataout=data.frame(dataout); } write.table(dataout, file=paste(filename,".txt",sep=""), quote=FALSE, sep="\t", col.names=names(dataout),row.names=FALSE, dec=".") return(dataout) } \end{lstlisting} \paragraph{\texorpdfstring{Script e Arquivos}{Script e Arquivos}} \label{sec:script_e_arquivos} \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/agrupacoluna2.r}{scriptfuncao\_agrupa.col}\\ \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/abs_costarj_401_edited1.txt}{arquivoteste01}\\ \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/abs_costarj_402_edited1.txt}{arquivoteste02}\\ \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/abs_costarj_405_edited1.txt}{arquivoteste03}\\ \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/abs_costarj_410_edited1.txt}{arquivoteste04}\\ \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/abs_costarj_411_edited1.txt}{arquivoteste05} \subsection{\texorpdfstring{Página Ajuda}{Pagina Ajuda}} \label{sec:pagina_ajuda} \href{media/bie5782/01_curso_atual/alunos/trabalho_final/bucci.andre/agrupacol_help.r}{agrupa.col HELP!}\lstset{frame=single} \begin{lstlisting} agrupa.col package:unkonw R Documentation Multiple Data Input Description Reads multiple files in table format of the same length and creates a data frame and a .txt file from the desired commom column (e.g. 2nd column of all files), with cases corresponding to lines and variables to the columns selected. This function was designed to be used with spectrophotometers data files after processing. By changing its arguments, it can be used with any type of file. Usage read.table(files, col, filename, wave=TRUE) Arguments files a list of the files which the data are to be read from. Each row of the table appears as one line of the file. If is not specified, will automatically list all files in current directory and use these to import the data. col a integer positive value indicating which column of the files should be used to group the data. only works for one specified column at a time. Multiple columns are not supported and each file generated will have the same column position from the multiple files. For more than one column selected, user must run for each different column. filename the name of the output file without any extensions. must be used under quote (e.g. "myfile"). wave logical, if TRUE (default), then the first column of the output file will be the wavelength values for the spectrophotometer files. Assuming a standard spectrophotometer file to have its first column as the reading wavelengths. If FALSE, the output file will be saved without the wavelengths. Details This function is an auxiliary way of reading spectrophotometer data into R. Unless is specified, all files from the current directory will be read in. can be a list containing the files names or a single file, in this case will save only the correspondent column from . All files provided in must have the same number of column and rows, since the data will be coerced in a data frame . For all effects, input data should be tabulation separated and with "." (dot) as decimal separator since is used to read the input files into the function. If isn not quoted, will not work and a warning message will follow. Values A data frame containing the specified column from all files read. Also, will save a .txt file into the working directory with the name provided in . The file will have separation based on tabulations, and decimal separator as ".". Warning If is 0 the following error message will appear: Error in names(dataout) = c(paste(files, names(data[coluna[1]]))) : 'names' attribute [1] must be the same length as the vector [0] If is not provided, the following error message will appear: Error in (a * b) + col : 'col' is missing If is not quoted, the following error message will appear: Error in paste(filename, ".txt", sep = "") : object 'object' not found Note This is a function to rapidly access spectrophotometer data from multiple files and could be used with any readable file, while attending the premisses provided above and changing arguments. References Crawley, M. J. (2007). Data Input. Chapter 3 of The R Book. eds M. J. Crawley. John Wiley & Sons, Ltd. See Also read.table(), list.files(), write.table(), data.frame() Author Andre Bucci bucci.andre@usp.br Examples test1=c(rep(1,3), rep(2,3), rep(3,3)) test2=c(rep("a",3), rep("b",3), rep("c",3)) test1=matrix(test1,3,3) test2=matrix(test2,3,3) write.table(test1, "test1.txt", sep="\t", dec=".") write.table(test2, "test2.txt", sep="\t", dec=".") files=list.files(pattern="test") agrupa.col(files, col=2, filename="agrupatest", wave=FALSE) \end{lstlisting} \end{document}