Skip to content

Instantly share code, notes, and snippets.

@DomBennett
Created February 6, 2018 10:42
Show Gist options
  • Save DomBennett/4597719580adf377fbf43d4988fe5847 to your computer and use it in GitHub Desktop.
Save DomBennett/4597719580adf377fbf43d4988fe5847 to your computer and use it in GitHub Desktop.
Take sequences from fasta file and write as separate files
# Take sequences from fasta file and write as separate files
# FUNCTION
readSqs <- function(fl) {
all_data <- readLines(fl)
sqs <- list()
for(i in seq_along(all_data)) {
bit <- all_data[[i]]
if(grepl(pattern='^>', x=bit)) {
nm <- sub(pattern='^>', '', x=bit)
sqs[[nm]] <- ''
} else {
sqs[[nm]] <- paste0(sqs[[nm]], bit)
}
}
sqs
}
# VARS
sqfl <- 'my_lovely_sequences.fasta'
# SCRIPT
sqs <- readSqs(sqfl) # read sequences from fasta
for(i in seq_along(sqs)) { # loop through each seq
nm <- names(sqs)[i] # get seq name
# create file path from name, make sure it exists
flpth <- file.path(paste0('probe', i), 'consensus')
if(!file.exists(flpth)) {
print(paste0('[', flpth, '] does not exist'))
next
}
flpth <- file.path(flpth, paste0(nm, '.fasta'))
if(file.exists(flpth)) {
print(paste0('[', flpth, '] already exists'))
next
}
fasta <- paste0('>', nm, '\n', sqs[[i]]) # create fasta text
cat(fasta, file=flpth) # write to file
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment