R/NexIntoFas.R

Defines functions NexIntoFas

Documented in NexIntoFas

#' Utility for turning a nexus file into fasta file in TOAST
#'
#'
#' @author Alex Dornburg, \email{dornburgalex@@gmail.com}
#' @keywords toast nexus phylip alignment
#' @param filename defaults to superalign.txt
#' @export
#' @return exports an alignment in classic phyllip format into a nexus file. This is designed for the superalign file generated by toast but will work on any alignment file formatted the same way.
#' @examples
#'(filename = "superalign.txt")

#' @return This function uses an aligned nexus file that is either in your working directory
#'         externalfile=TRUE or that has been read into memory, externalfile=false.
#'         This then converts it to a fasta format writing to file with user specified filename
#' @examples
#' NexIntoFas(nexusfile= mynexusdata, filename="file_name",externalfile=TRUE, tolower=FALSE)
NexIntoFas <-function(nexusfile ="mynexusdata", filename="file_name", externalfile=TRUE, tolower=FALSE){
	if (externalfile==TRUE){
		nexus<-tolower(readLines(nexusfile))
	 }
		else if (externalfile==FALSE){
			nexus <-nexusfile
		}
    if (tolower==TRUE){
        nexus<-tolower(nexus)
    }
    else if (tolower==FALSE){
        nexus <-nexus
    }
	#figure out end of nexus block and end of matrix
	endblocka<-which(str_detect(nexus,"matrix")==TRUE)
	nexus<-nexus[-c(1:endblocka)]
	endblockb<-which(str_detect(nexus,"end;")==TRUE)-1
	nexus<-nexus[-c(endblockb:length(nexus))]
	#standardize spaces
	nexus<-str_squish(nexus)
	#split into two strings
	nexus <-str_split(nexus, " ")
    initialize_blankfile<-paste("touch ",filename)
    system(initialize_blankfile)
    #filecon<- file(filename)
    sink(filename)
	for (i in 1:length(nexus)){
		cat(">", nexus[[i]][1])
		cat("\n")
		cat(nexus[[i]][2])
		cat("\n")
	}
    sink()
   }
carolinafishes/toast documentation built on Dec. 19, 2024, 12:47 a.m.