Home > front end >  Write each element of a vector in file separated by tab - R
Write each element of a vector in file separated by tab - R

Time:09-23

I need to prepare a file for a tool I am using. The file should have the structure

Mutant
Mutant:A
Expression
Gene_A:0.5 Gene_B:1 Gene_C:3
Weight: 5

I wrote the following function to create such a file, where the value for the mutant and weight are used as inputs in the function, while the expression values (ie. Gene_A: 0.5 ... Gene_C:3) are taken from a vector. In the final file, I need the expression values to be separated by \t.

prep_file <- function(mutant, expression, weight, file_name){
  sink(paste0(file_name))
  cat("Mutant\n")
  cat(mutant,"\n")
  cat("Expression\n")
  cat(expression)
  cat("\n")
  cat("Weight:",weight)
  sink()
}

That can be used as such:

expres_vec <- c("Gene_A:0.5","Gene_B:1","Gene_C:3")
prep_file("Mutant:A",expres_vec,"5","test")

To create the test file in the example above.

How can I replace the cat(expression) in order to write each element of the expres_vec separated by a tab?

CodePudding user response:

You can use the function paste with the collapse option. For example:

cat(paste(expres_vec, collpase = "\t"))

Where "\t" designates a tab (you can you any other character or regular expression here if needed).

Or in your function:

prep_file <- function(mutant, expression, weight, file_name){
  sink(paste0(file_name))
  cat("Mutant\n")
  cat(mutant,"\n")
  cat("Expression\n")
  cat(paste(expression, collpase = "\t"))
  cat("\n")
  cat("Weight:",weight)
  sink()
}

CodePudding user response:

You could list the arguments and name them with the formalArgs of the function, helpful especially if the output might get more lines i.e. arguments, in the future.

prep_file <- function(Mutant, Expression, Weight, file_name) {
  l <- list(mutant, expression, weight) |> setNames(paste0(formalArgs(prep_file)[1:3], ':'))
  invisible(Map(cat, lapply(names(l), paste0, '\n'), lapply(l, paste0, '\t'), '\n')) |>
    capture.output(file=file_name)
}

prep_file("Mutant:A", expres_vec, 5, "test")
# Mutant:
#   Mutant:A     
# Expression:
#   Gene_A:0.5   Gene_B:1    Gene_C:3    
# Weight:
#   5   

Not sure, where the indentation comes from, but actually it improves readability :)

  •  Tags:  
  • r
  • Related