R/write_kspace.R

###
### write_kspace.R
###
### dependencies: kstMatrix, openxlsx2, readODS, tools
###

write_kspace <- function (x, filename, format=NULL, sep=',') {
  if (inherits(x, "kspace"))
    mat <- as.binaryMatrix(x)
  else if (!inherits(x, "kmspace")) 
    stop(sprintf("%s must be of class %s or %s!",
                 dQuote("x"),
                 dQuote("kspace"),
                 dQuote("kmspace")
    ))
  else {
    mat <- x
  }

  ext <- file_ext(filename)
  if (is.null(format)) {
    if (ext == "csv") format <- "CSV"
    else if (ext == "xlsx") format <- "XLSX"
    else if (ext == "ods") format <- "ODS"
    else format <- "SRBT"
  } else {
    if ((ext == "csv") && (format != "CSV"))
      warning(sprintf('Storing file in "%s" format in .csv file!', format))
    else if ((ext == "ods") && (format != "ODS"))
      warning(sprintf('Storing file in "%s" format in .ods file!', format))
    else if ((ext == "xlsx") && (format != "XLSX"))
      warning(sprintf('Storing file in "%s" format in .xlsx file!', format))
    else if (format %in% c("CSV", "ODS", "XLSX") && tolower(format) != ext)
      warning(sprintf("Format specification '%s' and filename extension '%s' do nto fit together!",
                      format, ext))
  }
  
  size <- dim(mat)
  
  if (format == "CSV") {
    if (sep == ',') dec <- '.'
    else dec <- ','
    if (is.null(colnames(mat)))
      write.table(mat, filename, sep=sep, row.names=FALSE, col.names=FALSE)
    else
      write.table(mat, filename, sep=sep, row.names=FALSE, col.names=TRUE)
  } else if (format == "XLSX") {
    if (is.null(colnames(mat)))
      write_xlsx(as.data.frame(mat), file = filename, col.names=FALSE)
    else write_xlsx(as.data.frame(mat), file = filename)
  } else if (format == "ODS") {
    if (is.null(colnames(mat)))
      write_ods(as.data.frame(mat), path = filename, col_names=FALSE)
    else write_ods(as.data.frame(mat), path = filename)
  } else {
    con <- file(filename)
    if (is.null(con))
      stop(sprintf("Unable to open file %s.", dQuote(filename)))
    open(con, open="w")
    
    if (format == "SRBT")
      cat("#SRBT v2.0 space\n", file=con)
    
    if ((format == "SRBT") | (format == "KST")) {
      cat(sprintf("%d\n", size[2]), file=con)
      cat(sprintf("%d\n", size[1]), file=con)
    }
    else if (format != "matrix") {
      close(con)
      unlink(filename)
      warning(format)
      stop(sprintf("Space file must have format %s, %s %s, or %s.",
                   dQuote("SRBT"),
                   dQuote("KST"),
                   dQuote("matrix"),
                   "spreadsheet format"
      ))
    }
    
    colnames(mat) <- NULL
    write.table(mat, sep="", file=con, col.names=FALSE, row.names=FALSE)
    
    close(con)
  }
}

Try the kstIO package in your browser

Any scripts or data that you put into this service are public.

kstIO documentation built on March 8, 2026, 5:06 p.m.