diff --git a/.Rbuildignore b/.Rbuildignore index 8f5a419..6b566c2 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -1,2 +1,6 @@ ^ReadWriter\.Rproj$ ^\.Rproj\.user$ +^\.github$ +^Development$ +^AGENTS\.md$ +^CITATION\.cff$ diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml new file mode 100644 index 0000000..0a8b3b7 --- /dev/null +++ b/.github/workflows/claude.yml @@ -0,0 +1,25 @@ +name: Claude Code +on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + issues: + types: [opened, assigned] + pull_request_review: + types: [submitted] +jobs: + claude: + if: contains(github.event.comment.body, '@claude') || contains(github.event.issue.body, '@claude') || contains(github.event.review.body, '@claude') + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + issues: write + id-token: write + steps: + - uses: actions/checkout@v4 + with: { fetch-depth: 1 } + - uses: anthropics/claude-code-action@v1 + with: + claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index c8d53ca..ee9e03c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,45 +1,61 @@ -# History files +# R and RStudio local state .Rhistory .Rapp.history - -# Session Data files .RData - -# User-specific files +.RDataTmp .Ruserdata +.Rproj.user/ +*.Rproj +.Renviron -# Example code in package build process -*-Ex.R +# R serialized data +*.rds +*.RDS +*.rda +*.RData -# Output files from R CMD build +# R build and check output +*-Ex.R /*.tar.gz - -# Output files from R CMD check /*.Rcheck/ - -# RStudio files -.Rproj.user/ - -# produced vignettes +*_cache/ +/cache/ +*.utf8.md +*.knit.md vignettes/*.html vignettes/*.pdf -# OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3 +# Authentication and deployment metadata .httr-oauth +rsconnect/ -# knitr and R markdown default cache directories -*_cache/ -/cache/ +# Generated package documentation +docs/ -# Temporary files created by R markdown -*.utf8.md -*.knit.md +# Translation temporary files +po/*~ -# R Environment Variables -.Renviron +# Accidental analysis output +*.pdf +*.png + +# Local aliases and links +*alias + +# macOS Finder metadata +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes + +# Windows metadata +Thumbs.db +ehthumbs.db + +# Linux/HPC core dumps +core +core.* +core-* +*.core .Rproj.user -ReadWriter.Rproj -*.Rproj -ReadWriter.Rproj -ReadWriter.Rproj -*.Rproj diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..a94afd8 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,28 @@ +# AGENTS.md + +## Overview +ReadWriter is an R package providing convenience functions for reading from and writing to text-based data files. The package aims to streamline common I/O tasks and complements other tools in the `@vertesy` ecosystem. + +## Repository structure +- `R/` – source code. All exported functions live in `ReadWriter.R`; deprecated helpers are kept in `Deprecated.Functions.R`. +- `man/` – autogenerated documentation for functions (update with `devtools::document`). +- `Development/` – scripts used to build or maintain the package; not installed with the package. +- `DESCRIPTION` – package metadata and dependency declarations. +- `README.md` – installation instructions and a high-level overview. + +## Dependencies +- Requires the `@vertesy` package [`Stringendo` (>=0.5.0)](https://github.com/vertesy/Stringendo) and CRAN packages `gtools`, `openxlsx`, `qs`, and `readr`. +- Install `Stringendo` before installing ReadWriter: + ```r + devtools::install_github("vertesy/Stringendo", upgrade = FALSE) + ``` +- Add any new dependencies to the `Imports` field in `DESCRIPTION`. + +## Development guidelines +- Place new functions in `R/ReadWriter.R` and document them with roxygen comments. +- Run `R -q -e "devtools::document()"` to regenerate Rd files before committing. +- Verify the package with `R -q -e "devtools::check(document = FALSE)"`; checks should pass with no errors. +- There is currently no automated test suite. Manual testing of new functionality is encouraged. + +## Getting started +New contributors should read `README.md` for installation details and review `R/ReadWriter.R` to understand available functions. For broader context and utility helpers, explore the `Stringendo` package and other repositories in the `@vertesy` organization. diff --git a/CITATION.cff b/CITATION.cff index a96fa30..0944304 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -1,12 +1,12 @@ cff-version: 1.2.0 title: vertesy/ReadWriter Functions to read and write tabular data files conveniently. -version: v1.6.1 +version: v1.6.9 message: >- If you use this software, please cite it using these metadata. type: software authors: - given-names: Abel family-names: Vertesy - email: abel.vertesy@imba.oeaw.ac.at + email: av@imba.oeaw.ac.at affiliation: IMBA orcid: 'https://orcid.org/0000-0001-6075-5702' diff --git a/DESCRIPTION b/DESCRIPTION index 1cfdb5a..1b1aebc 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,11 +1,10 @@ Package: ReadWriter Title: ReadWriter -Version: 1.6.1 +Version: 1.6.9 Authors@R: person("Abel", "Vertesy", , "av@imba.oeaw.ac.at", role = c("aut", "cre")) -Author: Abel Vertesy [aut, cre] Description: ReadWriter is a set of R functions to read and write files - conveniently. Complements CodeAndRoll2. + conveniently. Builds on Stringendo and complements CodeAndRoll2. License: GPL-3 + file LICENSE BugReports: https://github.com/vertesy/ReadWriter/issues Depends: @@ -16,6 +15,6 @@ Imports: qs, readr Encoding: UTF-8 -Packaged: 2025-07-14 12:49:22.339709 +Packaged: 2026-08-25 16:41:37.734198 Roxygen: list(markdown = TRUE) -RoxygenNote: 7.3.1 +RoxygenNote: 7.3.2 diff --git a/R/list.of.functions.in.ReadWriter.det.md b/Development/CITATION.cff similarity index 100% rename from R/list.of.functions.in.ReadWriter.det.md rename to Development/CITATION.cff diff --git a/Development/Create_the_ReadWriter_Package.OLD.R b/Development/Create_the_ReadWriter_Package.OLD.R deleted file mode 100644 index 6bb66b9..0000000 --- a/Development/Create_the_ReadWriter_Package.OLD.R +++ /dev/null @@ -1,148 +0,0 @@ -###################################################################################################### -# Create_the_ReadWriter_Package.R -###################################################################################################### -# source("~/GitHub/Packages/ReadWriter/Development/Create_the_ReadWriter_Package.R") -rm(list = ls(all.names = TRUE)); -try(dev.off(), silent = TRUE) - -# Functions ------------------------ -# require("devtools") - - -# Setup ------------------------ -package.name <- "ReadWriter" -package.version <- "1.5.2" -setwd("~/GitHub/Packages/") - -RepositoryDir <- paste0("~/GitHub/Packages/", package.name, "/") -fname <- paste0(package.name, ".R") -package.FnP <- paste0(RepositoryDir, "R/", fname) - -BackupDir <- "~/GitHub/Packages/ReadWriter/Development/" -dir.create(BackupDir) - -DESCRIPTION <- list("Title" = "ReadWriter " - , "Author" = person(given = "Abel", family = "Vertesy", email = "av@imba.oeaw.ac.at", role = c("aut", "cre") ) - , "Authors@R" = 'person(given = "Abel", family = "Vertesy", email = "av@imba.oeaw.ac.at", role = c("aut", "cre") )' - , "Description" = "ReadWriter is a set of R functions to read and write files conveniently. Complements CodeAndRoll2." - , "License" = "GPL-3 + file LICENSE" - , "Version" = package.version - , "Packaged" = Sys.time() - , "Depends" = "Stringendo (>= 0.5.0)" - , "Remotes" = "github::vertesy/Stringendo" # https://cran.r-project.org/web/packages/devtools/vignettes/dependencies.html - # https://stackoverflow.com/questions/72908510/r-package-how-to-specify-a-dependency-version-that-is-only-available-on-github - , "Imports" = "openxlsx, gtools, readr, utils" - , "BugReports"= "https://github.com/vertesy/ReadWriter/issues" -) - - -setwd(RepositoryDir) -if ( !dir.exists(RepositoryDir) ) { create(path = RepositoryDir, description = DESCRIPTION, rstudio = TRUE) -} else { - getwd() - try(file.remove(c("DESCRIPTION","NAMESPACE", "ReadWriter.Rproj"))) - usethis::create_package(path = RepositoryDir, fields = DESCRIPTION, open = F) -} - - -# go and write fun's ------------------------------------------------------------------------ -# file.edit(package.FnP) - -# Create Roxygen Skeletons ------------------------ -# RoxygenReady(package.FnP) - -# replace output files ------------------------------------------------ -BackupOldFile <- (paste0(BackupDir, "Development", ".bac")) -AnnotatedFile <- (paste0(BackupDir, "Development", ".annot.R")) -file.copy(from = package.FnP, to = BackupOldFile, overwrite = TRUE) -# file.copy(from = AnnotatedFile, to = package.FnP, overwrite = TRUE) - -# Manual editing of descriptors ------------------------------------------------ -# file.edit(package.FnP) - -# Compile a package ------------------------------------------------ -setwd(RepositoryDir) -getwd() -devtools::document() -warnings() - -{ - "update cff version" - citpath <- paste0(RepositoryDir, 'CITATION.cff') - xfun::gsub_file(file = citpath, perl = T - , "^version: v.+", paste0("version: v", package.version)) -} - - -# Install your package ------------------------------------------------ -install(RepositoryDir, upgrade = F) - -# Test if you can install from github ------------------------------------------------ -pak::pkg_install("vertesy/ReadWriter") -# unload("ReadWriter") -# require("ReadWriter") -# # remove.packages("ReadWriter") - -# dev branch -# "devtools::install_github('vertesy/ReadWriter@read_excel', upgrade = F)" - - -# Check CRAN ------------------------------------------------ -check(RepositoryDir, cran = TRUE) -# as.package(RepositoryDir) -# # source("https://install-github.me/r-lib/desc") -# # library(desc) -# # desc$set("ReadWriter", "foo") -# # desc$get(ReadWriter) -# system("cd ~/GitHub/ReadWriter/; ls -a; open .Rbuildignore") - - -# Check package dependencies ------------------------------------------------ -{ - depFile = paste0(RepositoryDir, 'Development/Dependencies.R') - - (f.deps <- NCmisc::list.functions.in.file(filename = package.FnP)) - # clipr::write_clip(f.deps) - - sink(file = depFile); print(f.deps); sink() - p.deps <- gsub(x = names(f.deps), pattern = 'package:', replacement = '') - write(x = p.deps, file = depFile, append = T) - p.dep.declared <- trimws(unlist(strsplit(DESCRIPTION$Imports, ","))) - (p.dep.new <- sort(union( p.deps, p.dep.declared))) - # clipr::write_clip(p.dep.new) -} - -# Package styling, and visualization ------------------------------------------------ -{ - styler::style_pkg(RepositoryDir) - # styler::style_file("~/GitHub/Packages/ReadWriter/Development/02.Compile.the.ReadWriter.package.R") - - { - # Exploring the Structure and Dependencies of my R Package: - "works on an installed package!" - pkgnet_result <- pkgnet::CreatePackageReport(package.name) - fun_graph <- pkgnet_result$FunctionReporter$pkg_graph$"igraph" - - # devtools::load_all('~/GitHub/Packages/PackageTools/R/DependencyTools.R') - convert_igraph_to_mermaid(graph = fun_graph, openMermaid = T, copy_to_clipboard = T) - } - - if (F) { - # Add @importFrom statements - (FNP <- package.FnP) - PackageTools::add_importFrom_statements(FNP, exclude_packages = "") - add_importFrom_statements(FNP, exclude_packages = "") - } -} - - -if (F) { - "check dependency on gdata package" - require('gdata'); (fs.gdata <- ls("package:gdata")) - intersect(f.deps[[1]], fs.gdata) - - require('Stringendo'); (fs.Stringendo <- ls("package:Stringendo")) - intersect(f.deps[[1]], fs.Stringendo) - setdiff(f.deps[[1]], c(fs.Stringendo, fs.gdata)) - -} diff --git a/Development/Create_the_ReadWriter_Package.R b/Development/Create_the_ReadWriter_Package.R index dd6a84c..1749f15 100644 --- a/Development/Create_the_ReadWriter_Package.R +++ b/Development/Create_the_ReadWriter_Package.R @@ -27,8 +27,8 @@ devtools::install_local(repository.dir, upgrade = F) # Test if you can install from github ------------------------------------------------ -remote.path <- file.path(DESCRIPTION$'github.user', package.name) -pak::pkg_install(remote.path) +# remote.path <- file.path(DESCRIPTION$'github.user', package.name) +# pak::pkg_install(remote.path) devtools::install_github(repo = "vertesy/Seurat.utils", upgrade = F) @@ -46,7 +46,6 @@ devtools::check_man(repository.dir) checkres <- devtools::check(repository.dir, cran = FALSE) - # Automated Codebase linting to tidyverse style ------------------------------------------------ styler::style_pkg(repository.dir) @@ -85,11 +84,11 @@ if (F) { for (scriptX in ls.scripts.full.path) { PackageTools::list_of_funs_to_markdown(scriptX) } -file.edit(paste0(repository.dir, "R/list.of.functions.in.", package.name, ".det.md")) -file.edit(paste0(repository.dir, "README.md")) +file.edit(paste0(repository.dir, "/R/list.of.functions.in.", package.name, ".det.md")) +file.edit(paste0(repository.dir, "/README.md")) file.remove(paste0(repository.dir, "/R/list.of.functions.in.", package.name, ".det.md")) -r$PackageTools() +d$PackageTools() PackageTools::copy_github_badge("active") # Add badge to readme via clipboard file.edit(paste0(repository.dir, "README.md")) diff --git a/Development/Dependencies.R b/Development/Dependencies.R index ef1ec77..247d38f 100644 --- a/Development/Dependencies.R +++ b/Development/Dependencies.R @@ -1,35 +1,93 @@ +Dependency file generated on Tue Aug 25 16:40:26 2026 + +#################################################################################################### +Deprecated.Functions.R +#################################################################################################### $`character(0)` -[1] "createStyle" "na.replace" "read_csv" "read_delim" "read_tsv" -[6] "read.xls" "sheetNames" "write.xlsx" +[1] "sheetNames" $`package:base` - [1] "as.data.frame" "as.list" "as.vector" - [4] "c" "data.matrix" "dim" - [7] "dimnames" "grepl" "gsub" -[10] "is.na" "lapply" "length" -[13] "make.names" "missing" "names" -[16] "nchar" "paste0" "print" -[19] "range" "require" "return" -[22] "round" "rownames" "setwd" -[25] "substitute" "sum" "suppressWarnings" -[28] "system" "try" "unlist" + [1] ".Deprecated" "as.list" "data.matrix" "dimnames" "grepl" + [6] "gsub" "is.na" "lapply" "length" "missing" +[11] "names" "print" "require" "return" "round" +[16] "sum" "try" + +$`package:ReadWriter` +[1] "na.replace" + +$`package:Stringendo` +[1] "iprint" "kollapse" "percentage_formatter" + +character(0) +base +ReadWriter +Stringendo +#################################################################################################### +ReadWriter.R +#################################################################################################### +$`c("package:ReadWriter", "package:MarkdownHelpers", "package:Connectome.tools")` +[1] "write.simple.tsv" + +$`character(0)` +[1] "collapse_row" "esc_md_table_cell" "osXpath" +[4] "stri_detect" + +$`package:base` + [1] ".Deprecated" "all" "apply" + [4] "as.character" "as.data.frame" "as.vector" + [7] "basename" "c" "cbind" +[10] "character" "class" "colnames" +[13] "data.frame" "data.matrix" "dim" +[16] "dir.create" "dir.exists" "dirname" +[19] "duplicated" "file.exists" "get0" +[22] "getOption" "getwd" "gsub" +[25] "identical" "invisible" "is.character" +[28] "is.data.frame" "is.list" "is.logical" +[31] "is.matrix" "is.na" "is.null" +[34] "is.numeric" "is.vector" "isFALSE" +[37] "isTRUE" "lapply" "length" +[40] "list" "make.names" "match" +[43] "match.arg" "message" "missing" +[46] "names" "nchar" "ncol" +[49] "NCOL" "NROW" "nzchar" +[52] "on.exit" "options" "paste" +[55] "paste0" "print" "range" +[58] "rep" "require" "return" +[61] "rownames" "sapply" "seq_len" +[64] "stop" "stopifnot" "substitute" +[67] "substr" "suppressWarnings" "system" +[70] "try" "unlist" "warning" +[73] "which" "write" "writeLines" $`package:methods` [1] "is" $`package:ReadWriter` -[1] "FirstCol2RowNames" + [1] "as.simple.md.table" "column.2.row.names" "construct.file.path" + [4] "createStyle" "getSheetNames" "na.replace" + [7] "qread" "read_csv" "read_csv2" +[10] "read_delim" "read_tsv" "read.xlsx" +[13] "write.simple.xlsx" "write.xlsx" + +$`package:stats` +[1] "setNames" $`package:Stringendo` -[1] "iprint" "kollapse" "percentage_formatter" -[4] "ppp" "ww.FnP_parser" + [1] "fix_special_characters_bash" "FixPlotName" + [3] "idate" "ifExistsAndTrue" + [5] "iprint" "kollapse" + [7] "kppc" "kppws" + [9] "ParseFullFilePath" "ppp" +[11] "sppp" "spps" $`package:utils` [1] "head" "read.table" "write.table" +c("ReadWriter", "MarkdownHelpers", "Connectome.tools") character(0) base methods ReadWriter +stats Stringendo utils diff --git a/Development/Development.bac b/Development/Development.bac index 556d3ab..8b361af 100644 --- a/Development/Development.bac +++ b/Development/Development.bac @@ -14,7 +14,7 @@ #' @title Convert a Column to Row Names in a Tibble or DataFrame #' #' @description Converts the first column (or a specified column) of a dataframe or tibble into row names. -#' This function differs from `tibble::column_to_rownames` in that it takes column names or inices and +#' This function differs from `tibble::column_to_rownames` in that it takes column names or indices and #' it offers the option to sanitize row names using `make.names`, provides a warning if there are #' duplicated values in the row name column #' @@ -27,7 +27,7 @@ #' @param as_df Boolean indicating whether to convert the input to a dataframe if it's not already one. #' Default: TRUE. #' @param warn Warn user if row names pre-exist. -#' @param ... Pass arguments to make.names().. +#' @param ... Pass arguments to make.names(). #' @export column.2.row.names <- function( @@ -359,7 +359,7 @@ read.simple.csv <- function( # _________________________________________________________________________________________________ #' @title read.simple.ssv -#' @description Space separeted values. Read in a file with excel style data: +#' @description Space separated values. Read in a file with excel style data: #' rownames in col1, headers SHIFTED. The header should start with a #' TAB / First column name should be empty. #' @param ... Multiple simple variables to parse. diff --git a/Development/ReadWriter.orig.R b/Development/ReadWriter.orig.R index 55bdfde..bd43e80 100644 --- a/Development/ReadWriter.orig.R +++ b/Development/ReadWriter.orig.R @@ -78,7 +78,7 @@ read.simple.csv <- function(..., colnames = TRUE, coltypes = NULL, wRownames = return(read_in) } -read.simple.ssv <- function(..., sep_ = " ", colnames = TRUE, wRownames = TRUE, NaReplace = TRUE, coltypes = NULL) { # Space separeted values. Read in a file with excel style data: rownames in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty. +read.simple.ssv <- function(..., sep_ = " ", colnames = TRUE, wRownames = TRUE, NaReplace = TRUE, coltypes = NULL) { # Space separated values. Read in a file with excel style data: rownames in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty. pfn = kollapse(...) # merge path and filename read_in = suppressWarnings(readr::read_delim( pfn, delim = sep_, col_names = colnames, col_types = coltypes )) iprint("New variable dim: ", dim(read_in) - 0:1) diff --git a/Development/config.R b/Development/config.R index 60ebd10..eae80d0 100644 --- a/Development/config.R +++ b/Development/config.R @@ -3,9 +3,9 @@ DESCRIPTION <- list( package.name = "ReadWriter", - version = "1.6.1", + version = "1.6.9", title = "ReadWriter", - description = "ReadWriter is a set of R functions to read and write files conveniently. Complements CodeAndRoll2.", + description = "ReadWriter is a set of R functions to read and write files conveniently. Builds on Stringendo and complements CodeAndRoll2.", author.given = "Abel", author.family = "Vertesy", diff --git a/NAMESPACE b/NAMESPACE index ec03e82..035a34a 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -2,6 +2,7 @@ export(FirstCol2RowNames) export(FirstCol2RowNames.as.df) +export(as.simple.md.table) export(column.2.row.names) export(qs.2.table) export(read.simple) @@ -17,12 +18,11 @@ export(read.simple.xlsx) export(read.simple_char_list) export(write.simple) export(write.simple.append) +export(write.simple.md.table) export(write.simple.tsv) export(write.simple.vec) export(write.simple.xlsx) export(write.simplest) -importFrom(Stringendo,ParseFullFilePath) -importFrom(Stringendo,sppp) importFrom(gtools,na.replace) importFrom(openxlsx,createStyle) importFrom(openxlsx,getSheetNames) diff --git a/R/Deprecated.Functions.R b/R/Deprecated.Functions.R index 44b179b..1053249 100644 --- a/R/Deprecated.Functions.R +++ b/R/Deprecated.Functions.R @@ -1,17 +1,15 @@ # _________________________________________________________________________________________________ - - # _________________________________________________________________________________________________ #' @title read.simple.xls -#' @description Read multi-sheet excel files. row_namePos = NULL for automatic -#' names Look into: http://readxl.tidyverse.org/. -#' @param pfn Path and File name, Default: kollapse(...) -#' @param row_namePos Where is the rowname, Default: NULL +#' @description Read multi-sheet Excel files. `row_namePos = NULL` for automatic +#' names. See http://readxl.tidyverse.org/. +#' @param pfn Path and file name. Default: kollapse(...). +#' @param row_namePos Where is the row name? Default: NULL. #' @param ... Multiple simple variables to parse. -#' @param header_ Is there header? Default: TRUE -#' @param WhichSheets Which sheets to read in +#' @param header_ Is there a header? Default: TRUE. +#' @param WhichSheets Which sheets to read. #' @examples #' \dontrun{ #' if (interactive()) { @@ -22,14 +20,14 @@ #' \code{\link[gdata]{read.xls}} #' @export # #' @importFrom gdata read.xls sheetNames -read.simple.xls <- function(pfn = kollapse(...), row_namePos = NULL, ..., header_ = TRUE, WhichSheets) { +read.simple.xls <- function(pfn = Stringendo::kollapse(...), row_namePos = NULL, ..., header_ = TRUE, WhichSheets) { .Deprecated("read.simple.xlsx") if (!require("gdata")) { - print("Please install gplots: install.packages('gdata')") + print("Please install gdata: install.packages('gdata')") } if (grepl("^~/", pfn)) { - iprint("You cannot use the ~/ in the file path! It is replaced by '~/'.") + Stringendo::iprint("You cannot use the ~/ in the file path! It is replaced by '~/'.") pfn <- gsub(pattern = "^~/", replacement = "~/", x = pfn) } else { print(pfn) @@ -38,14 +36,14 @@ read.simple.xls <- function(pfn = kollapse(...), row_namePos = NULL, ..., header # merge path and filename TheSheetNames <- gdata::sheetNames(pfn, verbose = FALSE) NrSheets <- length(TheSheetNames) - iprint(NrSheets, "sheets in the file.") + Stringendo::iprint(NrSheets, "sheets in the file.") # ExpData = CodeAndRoll2::list.fromNames(TheSheetNames) ExpData <- as.list(TheSheetNames) names(ExpData) <- TheSheetNames RangeOfSheets <- if (missing(WhichSheets)) 1:NrSheets else WhichSheets for (i in RangeOfSheets) { - iprint("sheet", i) + Stringendo::iprint("sheet", i) # ExpData[[i]] = gdata::read.xls(pfn, sheet = i, row.names = row_namePos, header = header_) } # for lapply(ExpData, function(x) print(dimnames(x))) @@ -53,7 +51,6 @@ read.simple.xls <- function(pfn = kollapse(...), row_namePos = NULL, ..., header } - # _________________________________________________________________________________________________ @@ -126,14 +123,13 @@ read.simple.xls <- function(pfn = kollapse(...), row_namePos = NULL, ..., header #' - # _________________________________________________________________________________________________ #' @title convert.tsv.data -#' @description Fix NA issue in dataframes imported by the new read.simple.tsv. -#' Set na_rep to NA if you want to keep NA-s -#' @param df_by_read.simple.tsv Data frame (e.g. by read.simple.tsv). -#' @param digitz Number of digits when rounding up, Default: 2 -#' @param na_rep Replace NA?, Default: 0 +#' @description Fix NA issues in data frames imported by the new read.simple.tsv. +#' Set `na_rep` to NA if you want to keep NAs. +#' @param df_by_read.simple.tsv Data frame (e.g., by `read.simple.tsv`). +#' @param digitz Number of digits when rounding up. Default: 2. +#' @param na_rep Replace NA? Default: 0. #' @seealso #' \code{\link[gtools]{na.replace}} #' @importFrom gtools na.replace @@ -142,10 +138,9 @@ convert.tsv.data <- function(df_by_read.simple.tsv, digitz = 2, na_rep = 0) { DAT <- data.matrix(df_by_read.simple.tsv) SNA <- sum(is.na(DAT)) - try(iprint("Replaced NA values:", SNA, "or", percentage_formatter(SNA / length(DAT))), silent = TRUE) + try(Stringendo::iprint("Replaced NA values:", SNA, "or", Stringendo::percentage_formatter(SNA / length(DAT))), silent = TRUE) gtools::na.replace(round(DAT, digits = digitz), replace = na_rep) } - # _________________________________________________________________________________________________ diff --git a/R/ReadWriter.R b/R/ReadWriter.R index 4522b01..1e67a16 100644 --- a/R/ReadWriter.R +++ b/R/ReadWriter.R @@ -6,29 +6,28 @@ # devtools::document('~/GitHub/Packages/ReadWriter'); - # ____________________________________________________________________________________________ ---- ## Aux ------------------------------------------------------------------------------------------------- #' @title Convert a Column to Row Names in a Tibble or DataFrame #' -#' @description Converts the first column (or a specified column) of a dataframe or tibble into row names. -#' This function differs from `tibble::column_to_rownames` in that it takes column names or inices and -#' it offers the option to sanitize row names using `make.names`, provides a warning if there are -#' duplicated values in the row name column +#' @description Converts the first column (or a specified column) of a data frame or tibble into row names. +#' This function differs from `tibble::column_to_rownames` in that it takes column names or indices, +#' offers the option to sanitize row names using `make.names`, and provides a warning if there are +#' duplicated values in the row name column. #' -#' @param tibble A dataframe or tibble without row names. -#' Default: No default value, a dataframe must be provided. +#' @param tibble A data frame or tibble without row names. +#' Default: No default value; a data frame must be provided. #' @param rowname_column Index of the column to be used as row names. #' Default: 1. #' @param make_names Boolean indicating whether to call `make.names` to sanitize row names. #' Default: FALSE. -#' @param as_df Boolean indicating whether to convert the input to a dataframe if it's not already one. +#' @param as_df Boolean indicating whether to convert the input to a data frame if it's not already one. #' Default: TRUE. -#' @param warn Warn user if row names pre-exist. Default: TRUE. +#' @param warn Warn user if row names preexist. Default: TRUE. #' @param overwrite Overwrite row names if they already exist. Default: TRUE. #' -#' @param ... Pass arguments to make.names().. +#' @param ... Pass arguments to `make.names()`. #' @export column.2.row.names <- function(tibble, rowname_column = 1, @@ -41,14 +40,24 @@ column.2.row.names <- function(tibble, rowname_column = 1, # Assertions stopifnot( is.data.frame(tibble), - # is.numeric(rowname_column), - rowname_column > 0, - rowname_column <= ncol(tibble), - is.logical(make_names), is.logical(as_df) + is.logical(make_names), is.logical(as_df), + is.logical(warn), is.logical(overwrite) ) + if (is.numeric(rowname_column)) { + stopifnot(rowname_column >= 1, rowname_column <= ncol(tibble)) + col_idx <- rowname_column + } else if (is.character(rowname_column)) { + stopifnot(rowname_column %in% colnames(tibble)) + col_idx <- match(rowname_column, colnames(tibble)) + } else { + stop("`rowname_column` must be a numeric index or column name.") + } + if (!is.null(rownames(tibble))) { if (warn) { + old_warn <- getOption("warn") + on.exit(options(warn = old_warn), add = TRUE) options(warn = -1) # this should not be necessary warning("tibble/df already has row names:", immediate. = TRUE) print(head(rownames(tibble))) @@ -61,13 +70,14 @@ column.2.row.names <- function(tibble, rowname_column = 1, } # Extracting the specified column to be used as row names - row_names <- tibble[[rowname_column]] + row_names <- tibble[[col_idx]] # Check for duplicated row names - if (anyDuplicated(rowname_column)) { - is.duplicated <- rowname_column[which(duplicated(rowname_column))] + dup_idx <- which(duplicated(row_names)) + if (length(dup_idx) > 0) { + dup_vals <- row_names[dup_idx] warning( - length(is.duplicated), " duplicated entries in: ", substitute(rowname_column), + length(dup_vals), " duplicated entries in ", colnames(tibble)[col_idx], "\narg make_names = TRUE will enforce uniqueness" ) } @@ -78,7 +88,7 @@ column.2.row.names <- function(tibble, rowname_column = 1, } # Removing the rowname column from the dataframe - tibble <- tibble[, -rowname_column, drop = FALSE] + tibble <- tibble[, -col_idx, drop = FALSE] # Setting the row names if (overwrite) { @@ -96,15 +106,14 @@ column.2.row.names <- function(tibble, rowname_column = 1, } - # _________________________________________________________________________________________________ #' @title FirstCol2RowNames #' -#' @description Set First Col to Row Names -#' @param Tibble A dataframe without rownames (tibble style) -#' @param rownamecol rowname column, Default: 1 -#' @param make_names call make.names to remove weird characters, Default: FALSE -#' @param as.df Convert tibble to data frame? Default: TRUE +#' @description Set first column to row names. +#' @param Tibble A data frame without row names (tibble style). +#' @param rownamecol Row name column. Default: 1. +#' @param make_names Call `make.names` to remove unusual characters. Default: FALSE. +#' @param as.df Convert tibble to data frame? Default: TRUE. #' @export FirstCol2RowNames <- function(Tibble, rownamecol = 1, make_names = FALSE, as.df = TRUE) { .Deprecated("column.2.row.names") @@ -120,7 +129,7 @@ FirstCol2RowNames <- function(Tibble, rownamecol = 1, make_names = FALSE, as.df } rownames(Tibble) <- row.names - iprint("Rownames", head(row.names), "...") + Stringendo::iprint("Rownames", head(row.names), "...") return(Tibble) } @@ -128,10 +137,10 @@ FirstCol2RowNames <- function(Tibble, rownamecol = 1, make_names = FALSE, as.df # _________________________________________________________________________________________________ #' @title FirstCol2RowNames.as.df -#' @description Set First Col to Row Names -#' @param Tibble A dataframe without rownames (tibble style) -#' @param rownamecol rowname column, Default: 1 -#' @param make_names call make.names to remove weird characters, Default: FALSE +#' @description Set first column to row names. +#' @param Tibble A data frame without row names (tibble style). +#' @param rownamecol Row name column. Default: 1. +#' @param make_names Call `make.names` to remove unusual characters. Default: FALSE. #' @export FirstCol2RowNames.as.df <- function(Tibble, rownamecol = 1, make_names = FALSE) { @@ -149,13 +158,14 @@ FirstCol2RowNames.as.df <- function(Tibble, rownamecol = 1, make_names = FALSE) #' #' @description Constructs a complete file path using either provided manual file name and directory #' or defaults to processing a given filename and using the current working directory. +#' At least one of `filename` or `manual_file_name` must be supplied. #' #' @param filename The base file name to process. Default: NULL. #' @param suffix The file name suffix to be appended. Default: NULL. #' @param extension The file extension to be appended. Default: NULL. #' @param manual_file_name An optional manual specification for the file name. Default: NULL. #' @param manual_directory An optional manual specification for the directory. Default: NULL. -#' @param v verbose Print path? Default: TRUE. +#' @param v Print path if verbose? Default: TRUE. #' #' @return A string representing the constructed file path. #' @importFrom Stringendo sppp ParseFullFilePath @@ -165,30 +175,35 @@ FirstCol2RowNames.as.df <- function(Tibble, rownamecol = 1, make_names = FALSE) #' extension = "txt" #' ) construct.file.path <- function( - filename = NULL, - suffix = NULL, - extension = NULL, - manual_file_name = NULL, - manual_directory = NULL, - v = TRUE) { - filename <- as.character(filename) # unclear why thus bf needed. + filename = NULL, + suffix = NULL, + extension = NULL, + manual_file_name = NULL, + manual_directory = NULL, + v = TRUE +) { + if (!is.null(filename)) filename <- as.character(filename) # unclear why thus bf needed. # Input argument assertions stopifnot( is.null(filename) || is.character(filename), + is.null(suffix) || is.character(suffix), + is.null(extension) || is.character(extension), is.null(manual_file_name) || is.character(manual_file_name), is.null(manual_directory) || is.character(manual_directory), - is.null(extension) || is.character(extension) + !is.null(filename) || !is.null(manual_file_name) ) fname <- if (!is.null(manual_file_name)) manual_file_name else Stringendo::sppp(filename, suffix) out_dir <- if (!is.null(manual_directory)) manual_directory else getwd() + if (!dir.exists(out_dir)) dir.create(out_dir, recursive = TRUE, showWarnings = FALSE) + stopifnot(dir.exists(out_dir)) # Construct the full file path FnP <- Stringendo::ParseFullFilePath(out_dir, fname, extension) # Output assertion - stopifnot(is.character(FnP), nzchar(FnP)) + stopifnot(is.character(FnP), length(FnP) == 1, nzchar(FnP)) if (v) { try(message(osXpath(FnP))) @@ -204,8 +219,7 @@ construct.file.path <- function( # _________________________________________________________________________________________________ #' @title read.simple.vec -#' @description read.simple.vec -#' @description Read each line of a file to an element of a vector (read in new-line separated values, no header!). +#' @description Read each line of a file to an element of a vector (read in newline-separated values, no header!). #' @param ... Multiple simple variables to parse. #' @examples #' \dontrun{ @@ -217,14 +231,14 @@ construct.file.path <- function( read.simple.vec <- function(...) { pfn <- Stringendo::kollapse(...) # merge path and filename read_in <- as.vector(unlist(read.table(pfn, stringsAsFactors = FALSE, sep = "\n"))) - iprint(length(read_in), "elements") + Stringendo::iprint(length(read_in), "elements") return(read_in) } # _________________________________________________________________________________________________ #' @title read.simple -#' @description It is essentially read.table() with file/path parsing. +#' @description Essentially `read.table()` with file/path parsing. #' @param ... Multiple simple variables to parse. #' @examples #' \dontrun{ @@ -255,19 +269,19 @@ read.simple_char_list <- function(...) { pfn <- Stringendo::kollapse(...) # merge path and filename read_in <- unlist(read.table(pfn, stringsAsFactors = FALSE)) # iprint("New variable head: ", what(read_in)) - iprint("New variable head: ", is(read_in), "range", range(read_in)) + Stringendo::iprint("New variable head: ", is(read_in), "range", range(read_in)) return(read_in) } # _________________________________________________________________________________________________ #' @title read.simple.table -#' @description Read in a file. default: header defines colnames, no rownames. -#' For rownames give the col nr. with rownames, eg. 1 The header should start -#' with a TAB / First column name should be empty. +#' @description Read a file. Default: header defines column names, no row names. +#' For row names give the column number with row names, e.g., 1. The header should start +#' with a TAB; the first column name should be empty. #' @param ... Multiple simple variables to parse. -#' @param colnames Are there column names? Default: TRUE -#' @param coltypes What type of variables are in columns? Auto-guessing can be very slow. Default: NULL +#' @param colnames Are there column names? Default: TRUE. +#' @param coltypes What type of variables are in columns? Auto-guessing can be very slow. Default: NULL. #' @examples #' \dontrun{ #' if (interactive()) { @@ -284,25 +298,24 @@ read.simple.table <- function(..., colnames = TRUE, coltypes = NULL) { pfn <- Stringendo::kollapse(...) # merge path and filename # read_in = read.table( pfn , stringsAsFactors = FALSE, sep = "\t", header = colnames ) read_in <- readr::read_tsv(pfn, col_names = colnames, col_types = coltypes) - iprint("New variable dim: ", dim(read_in)) + Stringendo::iprint("New variable dim: ", dim(read_in)) read_in <- as.data.frame(gtools::na.replace(data.matrix(read_in), replace = 0)) return(read_in) } - # _________________________________________________________________________________________________ #' @title read.simple.tsv -#' @description Read in a file with excel style data: rownames in col1, -#' headers SHIFTED. The header should start with a TAB / First column name +#' @description Read in a file with Excel-style data: row names in column 1, +#' headers shifted. The header should start with a TAB; the first column name #' should be empty. #' @param ... Multiple simple variables to parse. -#' @param sep_ Separator character, Default: ' ' -#' @param colnames Are there column names?, Default: TRUE -#' @param wRownames With rownames?, Default: TRUE -#' @param coltypes What type of variables are in columns? Auto-guessing can be very slow., Default: NULL -#' @param NaReplace Replace NA-values?, Default: TRUE -#' @param asTibble Load as tibble or dataframe?, Default: FALSE (=load as df) +#' @param sep_ Separator character. Default: '\\t'. +#' @param colnames Are there column names? Default: TRUE. +#' @param wRownames With row names? Default: TRUE. +#' @param coltypes What type of variables are in columns? Auto-guessing can be very slow. Default: NULL. +#' @param NaReplace Replace NA values? Default: TRUE. +#' @param asTibble Load as tibble or data frame? Default: FALSE (load as data frame). #' @examples #' \dontrun{ #' if (interactive()) { @@ -316,38 +329,33 @@ read.simple.table <- function(..., colnames = TRUE, coltypes = NULL) { #' @importFrom readr read_tsv #' @importFrom gtools na.replace read.simple.tsv <- function( - ..., sep_ = "\t", colnames = TRUE, wRownames = TRUE, - coltypes = NULL, NaReplace = TRUE, asTibble = FALSE) { + ..., sep_ = "\t", colnames = TRUE, wRownames = TRUE, + coltypes = NULL, NaReplace = TRUE, asTibble = FALSE +) { pfn <- Stringendo::kollapse(...) # merge path and filename read_in <- suppressWarnings(readr::read_tsv(pfn, col_names = colnames, col_types = coltypes)) - iprint("New variable dim: ", dim(read_in) - 0:1) + Stringendo::iprint("New variable dim: ", dim(read_in) - 0:1) # if (wRownames) { read_in = FirstCol2RowNames(read_in, as.df = !asTibble ) } - if (wRownames) { - read_in <- column.2.row.names(read_in, as_df = !asTibble) - } + if (wRownames) read_in <- column.2.row.names(read_in, as_df = !asTibble) + if (NaReplace) read_in <- as.data.frame(gtools::na.replace(read_in, replace = 0)) - if (NaReplace) { - read_in <- as.data.frame(gtools::na.replace(read_in, replace = 0)) - } return(read_in) } - - # _________________________________________________________________________________________________ #' @title read.simple.csv -#' @description Read in a file with excel style data: rownames in col1, -#' headers SHIFTED. The header should start with a TAB / First column name +#' @description Read in a file with Excel-style data: row names in column 1, +#' headers shifted. The header should start with a TAB; the first column name #' should be empty. #' @param ... Multiple simple variables to parse. -#' @param colnames Are there column names?, Default: TRUE -#' @param coltypes What type of variables are in columns? Auto-guessing can be very slow., Default: NULL -#' @param wRownames With rownames?, Default: TRUE -#' @param NaReplace Replace NA-values?, Default: TRUE -#' @param asTibble Load as tibble or dataframe?, Default: FALSE (=load as df) -#' @param nmax Max number of rows to read, Default: Inf +#' @param colnames Are there column names? Default: TRUE. +#' @param coltypes What type of variables are in columns? Auto-guessing can be very slow. Default: NULL. +#' @param wRownames With row names? Default: TRUE. +#' @param NaReplace Replace NA values? Default: TRUE. +#' @param asTibble Load as tibble or data frame? Default: FALSE (load as data frame). +#' @param nmax Max number of rows to read. Default: Inf. #' @examples #' \dontrun{ #' if (interactive()) { @@ -361,41 +369,37 @@ read.simple.tsv <- function( #' @importFrom readr read_csv #' @importFrom gtools na.replace read.simple.csv <- function( - ..., colnames = TRUE, coltypes = NULL, wRownames = TRUE, - NaReplace = TRUE, asTibble = FALSE, nmax = Inf) { + ..., colnames = TRUE, coltypes = NULL, wRownames = TRUE, + NaReplace = TRUE, asTibble = FALSE, nmax = Inf +) { # browser() pfn <- Stringendo::kollapse(...) # merge path and filename read_in <- suppressWarnings(readr::read_csv(pfn, col_names = colnames, col_types = coltypes, n_max = nmax )) - iprint("New variable dim: ", dim(read_in) - 0:1) + Stringendo::iprint("New variable dim: ", dim(read_in) - 0:1) # if (wRownames) { read_in = FirstCol2RowNames(read_in) } - if (wRownames) { - read_in <- column.2.row.names(read_in, as_df = !asTibble) - } + if (wRownames) read_in <- column.2.row.names(read_in, as_df = !asTibble) + if (NaReplace) read_in <- as.data.frame(gtools::na.replace(read_in, replace = 0)) - if (NaReplace) { - read_in <- as.data.frame(gtools::na.replace(read_in, replace = 0)) - } return(read_in) } # _________________________________________________________________________________________________ #' @title read.simple.csv.named.vector #' -#' @description Read in a data frame (csv), and extact a value and a name column, and convert them -#' to a named vector. By default, it assumes the names in the first column and the values -#' excel style named vectors, names in col1, -#' headers SHIFTED. The header should start with a TAB / First column name -#' should be empty. +#' @description Read in a data frame (CSV), extract a value and a name column, and convert them +#' to a named vector. By default, it assumes the names are in the first column and the values in the second. +#' For Excel-style named vectors, names are in column 1 and headers are shifted. +#' The header should start with a TAB; the first column name should be empty. #' @param file Path to the *.csv file. -#' @param sep Separator character, Default: ';' alternative: ','. -#' @param col_names Are there column names?, Default: TRUE -#' @param value_col Column number of the values in the input data frame. Default: 2 -#' @param name_col Column number of the names in the input data frame. Default: 1 -#' @param ... Additional arguments passed to \code{\link[readr]{read_csv}} or read_csv2. +#' @param sep Separator character. Default: ';'; alternative: ','. +#' @param col_names Are there column names? Default: TRUE. +#' @param value_col Column number of the values in the input data frame. Default: 2. +#' @param name_col Column number of the names in the input data frame. Default: 1. +#' @param ... Additional arguments passed to \code{\link[readr]{read_csv}} or `read_csv2`. #' @examples #' \dontrun{ #' if (interactive()) { @@ -422,7 +426,7 @@ read.simple.csv.named.vector <- function(file, sep = ";", col_names = FALSE, vect <- df[[value_col]] names(vect) <- df[[name_col]] - message("New vectors length is: ", length(vect), "e.g. ", kppc(head(vect)), " ...") + message("New vectors length is: ", length(vect), "e.g. ", Stringendo::kppc(head(vect)), " ...") return(vect) } @@ -430,15 +434,16 @@ read.simple.csv.named.vector <- function(file, sep = ";", col_names = FALSE, # _________________________________________________________________________________________________ #' @title read.simple.ssv -#' @description Space separeted values. Read in a file with excel style data: -#' rownames in col1, headers SHIFTED. The header should start with a -#' TAB / First column name should be empty. +#' @description Space separated values. Read in a file with Excel-style data: +#' row names in column 1, headers shifted. The header should start with a +#' TAB; the first column name should be empty. #' @param ... Multiple simple variables to parse. -#' @param sep_ Separator character, Default: ' ' -#' @param colnames Are there column names?, Default: TRUE -#' @param wRownames With rownames?, Default: TRUE -#' @param NaReplace Replace NA-values?, Default: TRUE -#' @param coltypes What type of variables are in columns? Auto-guessing can be very slow., Default: NULL +#' @param sep_ Separator character. Default: ' '. +#' @param colnames Are there column names? Default: TRUE. +#' @param wRownames With row names? Default: TRUE. +#' @param NaReplace Replace NA values? Default: TRUE. +#' @param coltypes What type of variables are in columns? Auto-guessing can be very slow. Default: NULL. +#' @param asTibble Load as tibble or data frame? Default: FALSE (load as data frame). #' @examples #' \dontrun{ #' if (interactive()) { @@ -452,26 +457,24 @@ read.simple.csv.named.vector <- function(file, sep = ";", col_names = FALSE, #' @importFrom readr read_delim #' @importFrom gtools na.replace read.simple.ssv <- function( - ..., sep_ = " ", colnames = TRUE, wRownames = TRUE, NaReplace = TRUE, - coltypes = NULL) { + ..., sep_ = " ", colnames = TRUE, wRownames = TRUE, NaReplace = TRUE, + coltypes = NULL, asTibble = FALSE +) { pfn <- Stringendo::kollapse(...) # merge path and filename read_in <- suppressWarnings(readr::read_delim(pfn, delim = sep_, col_names = colnames, col_types = coltypes)) - iprint("New variable dim: ", dim(read_in) - 0:1) - if (wRownames) { - read_in <- FirstCol2RowNames(read_in) - } - if (NaReplace) { - read_in <- as.data.frame(gtools::na.replace(read_in, replace = 0)) - } + Stringendo::iprint("New variable dim: ", dim(read_in) - 0:1) + + if (wRownames) read_in <- column.2.row.names(read_in, as_df = !asTibble) + if (NaReplace) read_in <- as.data.frame(gtools::na.replace(read_in, replace = 0)) + return(read_in) } - # _________________________________________________________________________________________________ #' @title read.simple.tsv.named.vector -#' @description Read in a file with excel style named vectors, names in col1, -#' headers SHIFTED. The header should start with a TAB / First column name +#' @description Read in a file with Excel-style named vectors, names in column 1, +#' headers shifted. The header should start with a TAB; the first column name #' should be empty. #' @param ... Multiple simple variables to parse. #' @examples @@ -491,17 +494,16 @@ read.simple.tsv.named.vector <- function(...) { read_in <- readr::read_tsv(pfn) vect <- read_in[[2]] names(vect) <- read_in[[1]] - iprint("New vectors length is: ", length(vect)) + Stringendo::iprint("New vectors length is: ", length(vect)) return(vect) } - # _________________________________________________________________________________________________ #' @title Read a multi-sheet XLSX easily #' #' @description Reads specified sheets from an XLSX file into a list of data frames. -#' It allows customization of column names, row names, and trimming of white spaces. +#' It allows customization of column names, row names, and trimming of whitespace. #' #' @param pfn Path and filename of the XLSX file. #' Default: Constructed using `Stringendo::kollapse(...)`. @@ -509,10 +511,10 @@ read.simple.tsv.named.vector <- function(...) { #' Default: All sheets. #' @param col_names Logical, whether to use the first row as column names. #' Default: TRUE. -#' @param row_names Numeric, whether to convert a column to row names. -#' Default: 1. Use 0 for no conversion. Default: FALSE. -#' @param trim_ws Logical, whether to trim white spaces from column names. -#' @param ... Pass arguments to read.xlsx(). +#' @param row_names Numeric indicating which column to convert to row names. +#' Use 0 or FALSE for no conversion. Default: FALSE. +#' @param trim_ws Logical, whether to trim whitespace from column names. +#' @param ... Pass arguments to `read.xlsx()`. #' #' @return A list of data frames, each representing a sheet from the XLSX file. #' @importFrom openxlsx read.xlsx getSheetNames @@ -521,10 +523,11 @@ read.simple.tsv.named.vector <- function(...) { #' @export read.simple.xlsx <- function( - pfn = Stringendo::kollapse(...), which_sheets, - col_names = TRUE, row_names = FALSE, - trim_ws = TRUE - , ...) { + pfn = Stringendo::kollapse(...), which_sheets, + col_names = TRUE, row_names = FALSE, + trim_ws = TRUE, + ... +) { # Assertions for input arguments stopifnot(is.character(pfn), length(pfn) > 0) if (!missing(which_sheets)) stopifnot(is.numeric(which_sheets) | is.character(which_sheets)) @@ -569,9 +572,9 @@ read.simple.xlsx <- function( # ____________________________________________________________________________________________ ---- ## Writing files out ------------------------------------------------------------------------------ -#' @title Append or write a vector to standard file, one element per line. +#' @title Append or write a vector to a standard file, one element per line. #' -#' @description Alternative to clipboard. This function takes a vector and appends it +#' @description Alternative to the clipboard. This function takes a vector and appends it #' to a specified file. #' #' @param vec A vector to be written to the file. Default: `LETTERS[1:11]`. @@ -579,7 +582,7 @@ read.simple.xlsx <- function( #' @param header A string to be added to the header line (before the vector). Default: `NULL`. #' @param prefix A prefix to the header. Default: `kppws(substitute(vec), idate())`. #' @param file_path A string specifying the file path where the vector will be written. Default: -#' `"/groups/knoblich/Projects/connectomics/Analysis/__clipboard.txt"`. +#' path stored in `path_write_simplest` global variable, otherwise `"./__clipboard.txt"`. #' #' @examples #' \dontrun{ @@ -589,8 +592,8 @@ read.simple.xlsx <- function( #' @return A message indicating the length of the vector and the file path to which it was written. #' #' @export -write.simplest <- function(vec = LETTERS[1:11], append = TRUE, header = NULL, prefix = kppws(substitute(vec), idate()), - file_path = "/groups/knoblich/Projects/connectomics/Analysis/__clipboard.txt") { +write.simplest <- function(vec = LETTERS[1:11], append = TRUE, header = NULL, prefix = Stringendo::kppws(substitute(vec), Stringendo::idate()), + file_path = get0("path_write_simplest", ifnotfound = "./__clipboard.txt")) { stopifnot( is.vector(vec), is.character(file_path), @@ -604,20 +607,30 @@ write.simplest <- function(vec = LETTERS[1:11], append = TRUE, header = NULL, pr file = file_path, append = TRUE ) } + message(file_path) + message(file_path) - write(kppws(prefix, header), file = file_path, append = TRUE) + write(Stringendo::kppws(prefix, header), file = file_path, append = TRUE) write.table(vec, file = file_path, sep = "\n", row.names = FALSE, col.names = FALSE, quote = FALSE, append = append ) - message("Vector of length ", length(vec), " e.g.: ", kppc(head(vec)), ", is written to: \n", file_path) + message("Vector of length ", length(vec), " e.g.: ", Stringendo::kppc(head(vec)), ".") - guessed_local_path <- gsub( - x = file_path, - pattern = "/groups/knoblich/Projects/connectomics/Analysis/", - replacement = "/Volumes/Analysis/" - ) - message("open ", guessed_local_path) + message("\nsubl ", file_path) + + if (Stringendo::ifExistsAndTrue("onCBE")) { + attach <- paste0("smb://storage.imp.ac.at", dirname(file_path)) + message("\nAttach in Finder:\n", attach, "\n") + message("open ", Stringendo::spps("/Volumes/", basename(attach))) + } + + # guessed_local_path <- gsub( + # x = file_path, + # pattern = "/groups/knoblich/Projects/connectomics/Analysis/", + # replacement = "/Volumes/Analysis/" + # ) + # message("open ", guessed_local_path) } # write.simplest() @@ -637,7 +650,7 @@ write.simplest <- function(vec = LETTERS[1:11], append = TRUE, header = NULL, pr #' @param manual_file_name Manually defined filename, overrides automatic naming. Default: NULL. #' @param manual_directory Directory to save the file in, overrides default directory. Default: NULL. #' @param o If TRUE, opens the file after writing on OS X using 'system(open ...)'. Default: FALSE. -#' @param v verbose Print path? Default: TRUE. +#' @param v Print path if verbose? Default: TRUE. #' @return Outputs a .tsv file and optionally prints the length of the input data frame. #' @examples #' \dontrun{ @@ -662,7 +675,7 @@ write.simple <- function(input_df, filename = substitute(input_df), suffix = NUL FnP <- construct.file.path( v = v, - filename = FixPlotName(make.names(filename)), suffix = suffix, extension = extension, + filename = Stringendo::FixPlotName(make.names(filename)), suffix = suffix, extension = extension, manual_file_name = manual_file_name, manual_directory = manual_directory ) @@ -672,15 +685,14 @@ write.simple <- function(input_df, filename = substitute(input_df), suffix = NUL if (o) { system(paste0("open ", FnP), wait = FALSE) } - iprint("Length: ", length(input_df)) + Stringendo::iprint("Length: ", length(input_df)) } - # _________________________________________________________________________________________________ #' @title Write Simple Vector #' -#' @description Writes a vector-like R object to a file as newline separated values (.vec). +#' @description Writes a vector-like R object to a file as newline-separated values (.vec). #' The output filename can be auto-generated from the variable's name or manually specified. The file #' is saved in the specified output directory or the current working directory. The path and variable #' name can be passed separately and will be concatenated to form the filename. @@ -691,7 +703,9 @@ write.simple <- function(input_df, filename = substitute(input_df), suffix = NUL #' @param manual_file_name Manually defined filename, overrides automatic naming. Default: NULL. #' @param manual_directory Directory to save the file in, overrides default directory. Default: NULL. #' @param o If TRUE, opens the file after writing on OS X using 'system(open ...)'. Default: FALSE. -#' @param v verbose Print path? Default: TRUE. +#' @param v Print path if verbose? Default: TRUE. +#' @param make_names If TRUE, applies `make.names` to the filename. Generally safer, but it can, +#' e.g.: inadvarently change "_myFile" to "X_myFile". Default: TRUE. #' #' @return Outputs a .vec file and optionally prints the length of the input vector. #' @examples @@ -703,7 +717,7 @@ write.simple <- function(input_df, filename = substitute(input_df), suffix = NUL #' @export write.simple.vec <- function(input_vec, filename = substitute(input_vec), suffix = NULL, extension = "vec", manual_file_name = NULL, manual_directory = NULL, o = FALSE, - v = TRUE) { + v = TRUE, make_names = TRUE) { # Input argument assertions stopifnot( is.vector(input_vec), @@ -714,9 +728,10 @@ write.simple.vec <- function(input_vec, filename = substitute(input_vec), suffix is.logical(o) ) + if (make_names) filename <- make.names(filename) FnP <- construct.file.path( v = v, - filename = FixPlotName(make.names(filename)), suffix = suffix, extension = extension, + filename = Stringendo::FixPlotName(filename), suffix = suffix, extension = extension, manual_file_name = manual_file_name, manual_directory = manual_directory ) @@ -736,26 +751,26 @@ write.simple.vec <- function(input_vec, filename = substitute(input_vec), suffix # _________________________________________________________________________________________________ #' @title write.simple.tsv #' -#' @description Write out a matrix-like R-object WITH ROW- AND COLUMN- NAMES to a file with as tab separated -#' values (.tsv). Your output filename will be either the variable's name. The output file will be -#' located in "OutDir" specified by you at the beginning of the script, or under your current -#' working directory. You can pass the PATH and VARIABLE separately (in order), they will be -#' concatenated to the filename. If col.names = NA and row.names = TRUE a blank column name is added, +#' @description Write out a matrix-like R object with row and column names to a file as tab-separated +#' values (.tsv). The output filename will be either the variable's name or the one you provide. The output +#' file will be located in the directory specified at the beginning of the script or in your current +#' working directory. You can pass the path and variable separately (in order); they will be concatenated +#' to the filename. If `col.names = NA` and `row.names = TRUE`, a blank column name is added, #' which is the convention used for CSV files to be read by spreadsheets. -#' @param input_df Your Dataframe with row- and column-names -#' @param ... Pass any other argument to the kollapse() function used for file name. -#' @param separator Field separator, such as "," for csv -#' @param filename The base name for the output file. Default: Name of the input vector. -#' @param extension e.g.: tsv -#' @param suffix A suffix added to the filename, Default: NULL -#' @param manual_file_name Specify full filename if you do not want to name it by the variable name. +#' It can also write CSV files if you set the separator to ',' or ';'. +#' @param input_df Your data frame with row and column names. +#' @param separator Field separator, such as ',' for CSV. +#' @param filename The base name for the output file. Default: Name of the input data frame. +#' @param extension e.g., 'tsv'. +#' @param suffix A suffix added to the filename. Default: NULL. +#' @param manual_file_name Specify full filename if you do not want to name it after the variable. #' @param manual_directory Specify the directory where the file should be saved. -#' @param row_names Write row names? TRUE by default -#' @param col_names Write column names? NA by default, TRUE if row_names == FALSE -#' @param gzip Compress the file after saving? FALSE by default -#' @param o Open the file after saving? FALSE by default -#' @param v verbose Print path? Default: TRUE. -#' @param ... Additional arguments passed to write.table() +#' @param row_names Write row names? Default: TRUE. +#' @param col_names Write column names? Default: NA, set to TRUE if `row_names == FALSE`. +#' @param gzip Compress the file after saving? Default: FALSE. +#' @param o Open the file after saving? Default: FALSE. +#' @param v Print path if verbose? Default: TRUE. +#' @param ... Additional arguments passed to the kollapse() function used for the file name and to `write.table()`. #' #' @examples YourDataFrameWithRowAndColumnNames <- cbind("A" = rnorm(100), "B" = rpois(100, 8)) #' rownames(YourDataFrameWithRowAndColumnNames) <- letters[1:NROW(YourDataFrameWithRowAndColumnNames)] @@ -763,18 +778,21 @@ write.simple.vec <- function(input_vec, filename = substitute(input_vec), suffix #' #' @export write.simple.tsv <- function( - input_df, - separator = "\t", extension = "tsv", - filename = substitute(input_df), - suffix = NULL, - manual_file_name = NULL, - manual_directory = NULL, - row_names = TRUE, - col_names = NA, - gzip = FALSE, - o = FALSE, - v = TRUE, - ...) { + input_df, + separator = "\t", extension = "tsv", + filename = substitute(input_df), + suffix = NULL, + # prefix = NULL, + # subfolder = NULL, + manual_file_name = NULL, + manual_directory = NULL, + row_names = TRUE, + col_names = NA, + gzip = FALSE, + o = FALSE, + v = TRUE, + ... +) { # if (row_names == FALSE) { col_names <- TRUE @@ -789,7 +807,7 @@ write.simple.tsv <- function( FnP <- construct.file.path( v = v, - filename = FixPlotName(make.names(fname)), suffix = suffix, extension = extension, + filename = Stringendo::FixPlotName(make.names(fname)), suffix = suffix, extension = extension, manual_file_name = manual_file_name, manual_directory = manual_directory ) # print(FnP) @@ -806,18 +824,12 @@ write.simple.tsv <- function( } else { paste0("Length (of your vector): ", length(input_df)) } - iprint(printme) - if (o) { - system(paste0("open ", FnP), wait = FALSE) - } - if (gzip) { - system(paste0("gzip ", FnP), wait = FALSE) - } + Stringendo::iprint(printme) + if (o) system(paste0("open ", FnP), wait = FALSE) + if (gzip) system(paste0("gzip ", FnP), wait = FALSE) } - - # _________________________________________________________________________________________________ #' @title Write Simple Append #' @@ -832,7 +844,7 @@ write.simple.tsv <- function( #' @param manualFileName Manually defined filename, overrides automatic naming. Default: NULL. #' @param manualDirectory Directory to save the file in, overrides default directory. Default: NULL. #' @param o If TRUE, opens the file after writing on OS X using 'system(open ...)'. Default: FALSE. -#' @param v verbose Print path? Default: TRUE. +#' @param v Print path if verbose? Default: TRUE. #' #' @return Appends data to an existing .tsv file. #' @examples @@ -842,11 +854,11 @@ write.simple.tsv <- function( #' } #' } #' @export -write.simple.append <- function(input_df, filename = substitute(input_df), suffix = NULL, extension = "tsv", - manualFileName = NULL, manualDirectory = NULL, o = FALSE, - v = TRUE) { +write.simple.append <- function( + input_df, filename = substitute(input_df), suffix = NULL, extension = "tsv", + manualFileName = NULL, manualDirectory = NULL, o = FALSE, v = TRUE +) { stopifnot( - # is.data.frame(input_df), is.null(suffix) || is.character(suffix), is.character(extension), is.null(manualFileName) || is.character(manualFileName), @@ -856,7 +868,7 @@ write.simple.append <- function(input_df, filename = substitute(input_df), suffi FnP <- construct.file.path( v = v, - filename = FixPlotName(make.names(filename)), suffix = suffix, extension = extension, + filename = Stringendo::FixPlotName(make.names(filename)), suffix = suffix, extension = extension, manualFileName = manualFileName, manualDirectory = manualDirectory ) @@ -870,7 +882,6 @@ write.simple.append <- function(input_df, filename = substitute(input_df), suffi } - # _________________________________________________________________________________________________ # _________________________________________________________________________________________________ @@ -882,11 +893,11 @@ write.simple.append <- function(input_df, filename = substitute(input_df), suffi #' The function offers various styling and formatting options for the Excel file. #' #' @param named_list A list of data frames or matrices to write out. -#' Default: No default value, a list must be provided. +#' Default: No default value; a list must be provided. #' @param rowname_column The column name or index to use as row names in the Excel file. -#' Required, no default value. +#' Default: 1. #' @param filename The base name for the output file, derived from the 'named_list' variable if not specified. -#' Default: Derived using 'substitute(named_list)'. +#' Default: Derived using `substitute(named_list)`. #' @param suffix A suffix to be added to the output filename. Default: NULL. #' @param manual_file_name Manually defined filename, overrides automatic naming. Default: NULL. #' @param manual_directory Directory to save the file in, overrides default directory. Default: NULL. @@ -898,10 +909,11 @@ write.simple.append <- function(input_df, filename = substitute(input_df), suffi #' @param HeaderLineColor Color for the header line. Default: 'darkolivegreen3'. #' @param HeaderCharStyle Character style for the header (e.g., 'bold', 'italic', 'underline'). #' Default: 'bold'. -#' @param has_row_names Logical; if set to FALSE, converts the first column to row names. Default: TRUE +#' @param has_row_names Logical; if set to FALSE, converts the first column to row names. Default: TRUE. #' @param FreezeFirstRow Logical; if TRUE, freezes the first row in Excel. Default: TRUE. #' @param FreezeFirstCol Logical; if TRUE, freezes the first column in Excel. Default: FALSE. -#' @param v verbose Print path? Default: TRUE. +#' @param v Print path if verbose? Default: TRUE. +#' @param gzip Compress the file after saving? Default: FALSE. #' #' @examples #' \dontrun{ @@ -912,23 +924,24 @@ write.simple.append <- function(input_df, filename = substitute(input_df), suffi #' } #' @seealso #' \code{\link[openxlsx]{write.xlsx}} -#' @export #' @importFrom openxlsx write.xlsx createStyle +#' @export write.simple.xlsx write.simple.xlsx <- function( - named_list, - rowname_column = 1, # 'gene' # for Seurat df.markers - filename = substitute(named_list), - suffix = NULL, - manual_file_name = NULL, - manual_directory = NULL, - o = FALSE, - TabColor = "darkgoldenrod1", HeaderLineColor = "darkolivegreen3", - HeaderCex = 12, Creator = "", - HeaderCharStyle = c("bold", "italic", "underline")[1], - has_row_names = TRUE, - FreezeFirstRow = TRUE, FreezeFirstCol = FALSE, - v = TRUE) { + named_list, + rowname_column = 1, # 'gene' # for Seurat df.markers + filename = substitute(named_list), + suffix = NULL, + manual_file_name = NULL, + manual_directory = NULL, + o = FALSE, + TabColor = "darkgoldenrod1", HeaderLineColor = "darkolivegreen3", + HeaderCex = 12, Creator = "", + HeaderCharStyle = c("bold", "italic", "underline")[1], + has_row_names = TRUE, + FreezeFirstRow = TRUE, FreezeFirstCol = FALSE, + v = TRUE, gzip = FALSE +) { # Assertions for input arguments stopifnot( is.list(named_list), @@ -944,7 +957,7 @@ write.simple.xlsx <- function( ) # assign row names if required - if (!has_row_names) { + if (isFALSE(has_row_names)) { assignRownames <- function(x) column.2.row.names(df, rowname_column = rowname_column, make_names = TRUE) named_list <- lapply(named_list, assignRownames) message("Converting column ", rowname_column, " to row names: ", head(rownames(named_list[[1]]))) @@ -952,7 +965,7 @@ write.simple.xlsx <- function( FnP <- construct.file.path( v = v, - filename = FixPlotName(make.names(filename)), suffix = suffix, extension = "xlsx", + filename = Stringendo::FixPlotName(make.names(filename)), suffix = suffix, extension = "xlsx", manual_file_name = manual_file_name, manual_directory = manual_directory ) @@ -966,31 +979,168 @@ write.simple.xlsx <- function( # Output assertion stopifnot(file.exists(FnP)) - if (o) { - system(paste0("open ", fix_special_characters_bash(FnP)), wait = FALSE) - } + if (o) system(paste0("open ", Stringendo::fix_special_characters_bash(FnP)), wait = FALSE) + if (gzip) system(paste0("gzip ", Stringendo::fix_special_characters_bash(FnP)), wait = FALSE) } # fun +# ____________________________________________________________________________________________ ---- +## New addition: markdown ------------------------------------------------------------------------------ + + +# _________________________________________________________________________________________________ +#' @title as.simple.md.table +#' +#' @description Convert a data.frame / matrix-like object to minimal GitHub-flavored Markdown +#' table lines (header, separator, body). Pure formatter; does not write to disk. +#' +#' @param input_df Your data frame / matrix-like object. +#' @param row_names Include row names as the first column? Default: TRUE. +#' @param row_name_colname Column name for row names. Default: ''. +#' +#' @return Character vector of Markdown lines. +#' +#' @export +as.simple.md.table <- function( + input_df, + row_names = TRUE, + row_name_colname = "" +) { + stopifnot( + !missing(input_df), + isTRUE(row_names) || identical(row_names, FALSE), + is.character(row_name_colname), length(row_name_colname) == 1, !is.na(row_name_colname) + ) + + esc_md_table_cell <- function(x) { + x <- as.character(x) + x[is.na(x)] <- "" + x <- gsub("\\\\", "\\\\\\\\", x, perl = TRUE) # escape backslash + x <- gsub("\\|", "\\\\|", x, perl = TRUE) # escape pipe + x <- gsub("\r\n|\n|\r", "
", x, perl = TRUE) # preserve line breaks + x <- gsub("\t", " ", x, perl = TRUE) # tabs to spaces + x + } + + df <- if (is.data.frame(input_df)) input_df else as.data.frame(input_df, check.names = FALSE) + + if (isTRUE(row_names)) { + rn <- rownames(df) + if (is.null(rn)) rn <- seq_len(NROW(df)) + df <- cbind(setNames(data.frame(rn, stringsAsFactors = FALSE), row_name_colname), df) + } + + collapse_row <- function(x) paste(x, collapse = " | ") + + headers <- colnames(df) + if (is.null(headers)) headers <- rep("", NCOL(df)) + + c( + collapse_row(esc_md_table_cell(headers)), + collapse_row(rep("--", length(headers))), + if (NROW(df)) apply(df, 1, function(r) collapse_row(esc_md_table_cell(r))) else character(0) + ) +} + + +# _________________________________________________________________________________________________ +#' @title write.simple.md.table +#' +#' @description Write an R data.frame / matrix-like object to disk as a minimal GitHub-flavored +#' Markdown table (.md). +#' +#' @param input_df Your data frame / matrix-like object. +#' @param filename The base name for the output file. Default: Name of the input data frame. +#' @param extension File extension. Default: 'md'. +#' @param suffix A suffix added to the filename. Default: NULL. +#' @param manual_file_name Specify full filename if you do not want to name it after the variable. +#' @param manual_directory Specify the directory where the file should be saved. +#' @param row_names Include row names as the first column? Default: TRUE. +#' @param row_name_colname Column name for row names. Default: ''. +#' @param o Open the file after saving? Default: FALSE. +#' @param v Print path if verbose? Default: TRUE. +#' @param ... Additional arguments passed to the kollapse() function used for the file name. +#' +#' @examples +#' df <- data.frame( +#' Name = c("Alice", "Bob | The Builder", NA, "Eve\nNewline"), +#' Age = c(30, 25, 28, NA), +#' Note = c("Loves R\\Markdown", "Enjoys building\tthings", "No special chars", "Line1\r\nLine2"), +#' stringsAsFactors = FALSE, +#' check.names = FALSE +#' ) +#' write.simple.md.table(df, manual_file_name = "example_table.md", row_names = TRUE) +#' +#' @export +write.simple.md.table <- function( + input_df, + extension = "md", + filename = substitute(input_df), + suffix = NULL, + manual_file_name = NULL, + manual_directory = NULL, + row_names = TRUE, + row_name_colname = "", + o = FALSE, + v = TRUE, + ... +) { + stopifnot( + !missing(input_df), + is.character(extension), length(extension) == 1, nzchar(extension), + isTRUE(row_names) || identical(row_names, FALSE), + is.character(row_name_colname), length(row_name_colname) == 1, !is.na(row_name_colname), + isTRUE(o) || identical(o, FALSE), + isTRUE(v) || identical(v, FALSE) + ) + + md_lines <- as.simple.md.table( + input_df, + row_names = row_names, + row_name_colname = row_name_colname + ) + + # Safe, scalar filename (avoid kollapse() vector explosions) + fname <- Stringendo::kollapse(..., print = FALSE) + if (length(fname) != 1 || is.na(fname) || nchar(fname) < 2) fname <- as.character(filename)[1] + fname <- substr(as.character(fname)[1], 1, 180) + + FnP <- construct.file.path( + v = v, + filename = Stringendo::FixPlotName(make.names(fname)), + suffix = suffix, + extension = extension, + manual_file_name = manual_file_name, + manual_directory = manual_directory + ) + + dir.create(dirname(FnP), recursive = TRUE, showWarnings = FALSE) + writeLines(md_lines, con = FnP, useBytes = TRUE) + + Stringendo::iprint(paste0("Dim: ", paste(dim(as.data.frame(input_df)), collapse = " x "))) + if (isTRUE(o)) system(paste0("open ", FnP), wait = FALSE) + + invisible(FnP) +} + # ____________________________________________________________________________________________ ---- ## Reexport files ------------------------------------------------------------------------------ #' @title Convert and save a .qs file to different formats #' -#' @description -#' This function reads in a `.qs` file and resaves it as either a `.tsv`, `.csv`, semicolon-separated +#' @description Reads in a `.qs` file and resaves it as either a `.tsv`, `.csv`, semicolon-separated #' `.csv` (csv2), or Excel file based on the `out_file` argument. #' -#' @param path A character string specifying the path to the `.qs` file. Default: none. +#' @param path A character string specifying the path to the `.qs` file. Default: None. #' @param out_file A character string specifying the output file format. One of `"tsv"` (default), -#' `"csv"`, `"csv2"` (semicolon-separated), or `"excel"`. Default: `"tsv"`. +#' `"csv"`, `"csv2"` (semicolon-separated), or `"excel"`. #' #' @return The function does not return a value but writes the file to disk in the specified format. #' #' @importFrom qs qread -#' @export #' +#' @export qs.2.table qs.2.table <- function(path, out_file = c("tsv", "csv", "csv2", "excel")[1]) { # Ensure that the file exists and is a .qs file @@ -1003,11 +1153,11 @@ qs.2.table <- function(path, out_file = c("tsv", "csv", "csv2", "excel")[1]) { data <- qs:qread(path) # Determine the output file extension and write the file based on the output format - path_out <- ppp(base_filename, out_file) + path_out <- Stringendo::ppp(base_filename, out_file) if (out_file == "excel") { # out_path <- ppp(base_filename, "xlsx") - ppp(base_filename, out_file) + Stringendo::ppp(base_filename, out_file) ReadWriter::write.simple.xlsx(data, out_path) } diff --git a/R/list.of.functions.in.Deprecated.Functions.det.md b/R/list.of.functions.in.Deprecated.Functions.det.md deleted file mode 100644 index 4e9bf75..0000000 --- a/R/list.of.functions.in.Deprecated.Functions.det.md +++ /dev/null @@ -1,5 +0,0 @@ -## List of Functions in Deprecated.Functions.R (1) -Updated: 2024/10/24 15:07 -- #### 1 `#' FUNX()` -read.simple.xls. Read multi-sheet excel files. row_namePos = NULL for automatic names Look into: http://readxl.tidyverse.org/. - diff --git a/R/list.of.functions.in.ReadWriter.md b/R/list.of.functions.in.ReadWriter.md deleted file mode 100644 index 7506f26..0000000 --- a/R/list.of.functions.in.ReadWriter.md +++ /dev/null @@ -1,69 +0,0 @@ -## List of Functions (21) -## List of Functions in ReadWriter.R (21) -Updated: 2024/10/24 15:08 -- #### 1 `column.2.row.names()` -Convert a Column to Row Names in a Tibble or DataFrame. Converts the first column (or a specified column) of a dataframe or tibble into row names. - -- #### 2 `FirstCol2RowNames()` -FirstCol2RowNames. Set First Col to Row Names - -- #### 3 `FirstCol2RowNames.as.df()` -FirstCol2RowNames.as.df. Set First Col to Row Names - -- #### 4 `construct.file.path()` -Construct File Path. Constructs a complete file path using either provided manual file name and directory - -- #### 5 `read.simple.vec()` -read.simple.vec. read.simple.vec - -- #### 6 `read.simple()` -read.simple. Read each line of a file to an element of a vector (read in new-line separated values, no header!). - -- #### 7 `read.simple_char_list()` -read.simple_char_list. It is essentially read.table() with file/path parsing. - -- #### 8 `read.simple.table()` -read.simple.table. Read in a file. - -- #### 9 `read.simple.tsv()` -read.simple.tsv. Read in a file. default: header defines colnames, no rownames. - -- #### 10 `read.simple.csv()` -read.simple.csv. Read in a file with excel style data: rownames in col1, - -- #### 11 `read.simple.csv.named.vector()` -read.simple.csv.named.vector. Read in a file with excel style data: rownames in col1, - -- #### 12 `read.simple.ssv()` -read.simple.ssv. Read in a data frame (csv), and extact a value and a name column, and convert them - -- #### 13 `read.simple.tsv.named.vector()` -read.simple.tsv.named.vector. Space separeted values. Read in a file with excel style data: - -- #### 14 `read.simple.xlsx()` -Read a multi-sheet XLSX easily. Read in a file with excel style named vectors, names in col1, - -- #### 15 `write.simplest()` -Append or write a vector to standard file, one element per line.. Reads specified sheets from an XLSX file into a list of data frames. - -- #### 16 `write.simple()` -Write Simple. Alternative to clipboard. This function takes a vector and appends it - -- #### 17 `write.simple.vec()` -Write Simple Vector. Writes a matrix-like R object (e.g., a data frame) to a file as tab-separated - -- #### 18 `write.simple.tsv()` -write.simple.tsv. Writes a vector-like R object to a file as newline separated values (.vec). - -- #### 19 `write.simple.append()` -Write Simple Append. Write out a matrix-like R-object WITH ROW- AND COLUMN- NAMES to a file with as tab separated - -- #### 20 `write.simple.xlsx()` -Write Simple XLSX. Appends a data frame without row names to an existing .tsv file with the same number - -- #### 21 ` assignRownames()` -Convert and save a .qs file to different formats. Write out a list of matrices or data frames with row and column names - -- #### 22 `qs.2.table()` -NA. - diff --git a/README.md b/README.md index 8163a6c..431cb94 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,14 @@ Complements the new [CodeAndRoll2](https://github.com/vertesy/CodeAndRoll2). ## News -- The underlying `gdata` removed `read.xls`, and this is resolved in `v1.0.0` by using `openxlsx`. -- As of 11/2023 you may need `install_github(repo = "vertesy/ReadWriter@main")` instead of `install_github(repo = "vertesy/ReadWriter")` to install the package on some platforms. +### !!! Installation NEWS +#### `qs` dependency +- Until I update the code to [`qs2`]([url](https://github.com/qsbase/qs2)), you have to install `qs` [from github]([url](https://github.com/qsbase/qs)): +`remotes::install_cran("qs", type = "source", configure.args = "--with-simd=AVX2")` +- Unfortunately as of R4.6.0 `qs` is reportedy fails to install on R4.6.x on Windows. +- Solution: **Use R4.5.x until I can upgrade the package** + +

@@ -17,11 +23,11 @@ Install directly from **GitHub** via **devtools** with one R command: ```R # install.packages("devtools"); # If you don't have it. require("devtools") -devtools::install_github(repo = "vertesy/Stringendo", upgrade = F) -devtools::install_github(repo = "vertesy/ReadWriter") +devtools::install_github(repo = "vertesy/Stringendo", ref = "main", upgrade = F) +devtools::install_github(repo = "vertesy/ReadWriter", ref = "main") "As of 11/2023 you may need:" -devtools::install_github(repo = "vertesy/ReadWriter@main") +devtools::install_github(repo = "vertesy/ReadWriter@main", ref = "main") ``` ...then simply load the package: @@ -43,66 +49,123 @@ source("https://raw.githubusercontent.com/vertesy/ReadWriter/main/R/ReadWriter.R *If you encounter a **bug**, something doesn't work or unclear, please let me know by raising an issue on [ReadWriter](https://github.com/vertesy/ReadWriter/issues) – Please check if it has been asked.* -## List of Functions in ReadWriter.R (20) -Updated: 2024/10/24 13:48 +## List of Functions in ReadWriter.R (22) + +Updated: 2026/08/25 16:40 - #### 1 `column.2.row.names()` -Convert a Column to Row Names in a Tibble or DataFrame. Converts the first column (or a specified column) of a dataframe or tibble into row names. This function differs from `tibble::column_to_rownames` in that it takes column names or inices and it offers the option to sanitize row names using `make.names`, provides a warning if there are duplicated values in the row name column + + Convert a Column to Row Names in a Tibble or DataFrame. Converts the first column (or a specified column) of a data frame or tibble into row names. This function differs from `tibble::column_to_rownames` in that it takes column names or indices, offers the option to sanitize row names using `make.names`, and provides a warning if there are duplicated values in the row name column. - #### 2 `FirstCol2RowNames()` -FirstCol2RowNames. Set First Col to Row Names + + FirstCol2RowNames. Set first column to row names. - #### 3 `FirstCol2RowNames.as.df()` -FirstCol2RowNames.as.df. Set First Col to Row Names + + FirstCol2RowNames.as.df. Set first column to row names. - #### 4 `construct.file.path()` -Construct File Path. Constructs a complete file path using either provided manual file name and directory or defaults to processing a given filename and using the current working directory. + + Construct File Path. Constructs a complete file path using either provided manual file name and directory or defaults to processing a given filename and using the current working directory. At least one of `filename` or `manual_file_name` must be supplied. - #### 5 `read.simple.vec()` -read.simple.vec. Read each line of a file to an element of a vector (read in new-line separated values, no header!). + + read.simple.vec. Read each line of a file to an element of a vector (read in newline-separated values, no header!). - #### 6 `read.simple()` -read.simple. It is essentially read.table() with file/path parsing. + + read.simple. Essentially `read.table()` with file/path parsing. - #### 7 `read.simple_char_list()` -read.simple_char_list. Read in a file. + + read.simple_char_list. Read in a file. - #### 8 `read.simple.table()` -read.simple.table. Read in a file. default: header defines colnames, no rownames. For rownames give the col nr. with rownames, eg. 1 The header should start with a TAB / First column name should be empty. + + read.simple.table. Read a file. Default: header defines column names, no row names. For row names give the column number with row names, e.g., 1. The header should start with a TAB; the first column name should be empty. - #### 9 `read.simple.tsv()` -read.simple.tsv. Read in a file with excel style data: rownames in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty. + + read.simple.tsv. Read in a file with Excel-style data: row names in column 1, headers shifted. The header should start with a TAB; the first column name should be empty. - #### 10 `read.simple.csv()` -read.simple.csv. Read in a file with excel style data: rownames in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty. + + read.simple.csv. Read in a file with Excel-style data: row names in column 1, headers shifted. The header should start with a TAB; the first column name should be empty. - #### 11 `read.simple.csv.named.vector()` -read.simple.csv.named.vector. Read in a data frame (csv), and extact a value and a name column, and convert them to a named vector. By default, it assumes the names in the first column and the values excel style named vectors, names in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty. + + read.simple.csv.named.vector. Read in a data frame (CSV), extract a value and a name column, and convert them to a named vector. By default, it assumes the names are in the first column and the values in the second. For Excel-style named vectors, names are in column 1 and headers are shifted. The header should start with a TAB; the first column name should be empty. - #### 12 `read.simple.ssv()` -read.simple.ssv. Space separeted values. Read in a file with excel style data: rownames in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty. + + read.simple.ssv. Space separated values. Read in a file with Excel-style data: row names in column 1, headers shifted. The header should start with a TAB; the first column name should be empty. - #### 13 `read.simple.tsv.named.vector()` -read.simple.tsv.named.vector. Read in a file with excel style named vectors, names in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty. + + read.simple.tsv.named.vector. Read in a file with Excel-style named vectors, names in column 1, headers shifted. The header should start with a TAB; the first column name should be empty. - #### 14 `read.simple.xlsx()` -Read a multi-sheet XLSX easily. Reads specified sheets from an XLSX file into a list of data frames. It allows customization of column names, row names, and trimming of white spaces. + + Read a multi-sheet XLSX easily. Reads specified sheets from an XLSX file into a list of data frames. It allows customization of column names, row names, and trimming of whitespace. - #### 15 `write.simplest()` -Append or write a vector to standard file, one element per line.. Alternative to clipboard. This function takes a vector and appends it to a specified file. + + Append or write a vector to a standard file, one element per line.. Alternative to the clipboard. This function takes a vector and appends it to a specified file. - #### 16 `write.simple()` -Write Simple. Writes a matrix-like R object (e.g., a data frame) to a file as tab-separated values (.tsv). The output filename can be auto-generated from the variable's name or manually specified. The file is saved in the specified output directory or the current working directory. The path and variable name can be passed separately and will be concatenated to form the filename. + + Write Simple. Writes a matrix-like R object (e.g., a data frame) to a file as tab-separated values (.tsv). The output filename can be auto-generated from the variable's name or manually specified. The file is saved in the specified output directory or the current working directory. The path and variable name can be passed separately and will be concatenated to form the filename. - #### 17 `write.simple.vec()` -Write Simple Vector. Writes a vector-like R object to a file as newline separated values (.vec). The output filename can be auto-generated from the variable's name or manually specified. The file is saved in the specified output directory or the current working directory. The path and variable name can be passed separately and will be concatenated to form the filename. + + Write Simple Vector. Writes a vector-like R object to a file as newline-separated values (.vec). The output filename can be auto-generated from the variable's name or manually specified. The file is saved in the specified output directory or the current working directory. The path and variable name can be passed separately and will be concatenated to form the filename. - #### 18 `write.simple.tsv()` -write.simple.tsv. Write out a matrix-like R-object WITH ROW- AND COLUMN- NAMES to a file with as tab separated values (.tsv). Your output filename will be either the variable's name. The output file will be located in "OutDir" specified by you at the beginning of the script, or under your current working directory. You can pass the PATH and VARIABLE separately (in order), they will be concatenated to the filename. If col.names = NA and row.names = TRUE a blank column name is added, which is the convention used for CSV files to be read by spreadsheets. + + write.simple.tsv. Write out a matrix-like R object with row and column names to a file as tab-separated values (.tsv). The output filename will be either the variable's name or the one you provide. The output file will be located in the directory specified at the beginning of the script or in your current working directory. You can pass the path and variable separately (in order); they will be concatenated to the filename. If `col.names = NA` and `row.names = TRUE`, a blank column name is added, which is the convention used for CSV files to be read by spreadsheets. It can also write CSV files if you set the separator to ',' or ';'. - #### 19 `write.simple.append()` -Write Simple Append. Appends a data frame without row names to an existing .tsv file with the same number of columns. The output filename is auto-generated from the variable's name or manually specified. The file is saved in the specified output directory or the current working directory. The path and variable name can be passed separately and will be concatenated to form the filename. + + Write Simple Append. Appends a data frame without row names to an existing .tsv file with the same number of columns. The output filename is auto-generated from the variable's name or manually specified. The file is saved in the specified output directory or the current working directory. The path and variable name can be passed separately and will be concatenated to form the filename. - #### 20 ` assignRownames()` -Write Simple XLSX. Write out a list of matrices or data frames with row and column names to an Excel (.xlsx) file. The output filename is generated based on the provided parameters and stored in the specified output directory or the current working directory. The function offers various styling and formatting options for the Excel file. + Write Simple XLSX. Write out a list of matrices or data frames with row and column names to an Excel (.xlsx) file. The output filename is generated based on the provided parameters and stored in the specified output directory or the current working directory. The function offers various styling and formatting options for the Excel file. + +- #### 21 ` collapse_row()` + + as.simple.md.table. Convert a data.frame / matrix-like object to minimal GitHub-flavored Markdown table lines (header, separator, body). Pure formatter; does not write to disk. + +- #### 22 `write.simple.md.table()` + + write.simple.md.table. Write an R data.frame / matrix-like object to disk as a minimal GitHub-flavored Markdown table (.md). + + + +--- +## Function relationships +> (of connected functions) + +```mermaid + flowchart LR + + write.simple.vec(write.simple.vec) --> construct.file.path(construct.file.path) + write.simple.md.table(write.simple.md.table) --> as.simple.md.table(as.simple.md.table) + write.simple.md.table(write.simple.md.table) --> construct.file.path(construct.file.path) + write.simple.append(write.simple.append) --> construct.file.path(construct.file.path) + write.simple(write.simple) --> construct.file.path(construct.file.path) + read.simple.xlsx(read.simple.xlsx) --> column.2.row.names(column.2.row.names) + read.simple.tsv(read.simple.tsv) --> column.2.row.names(column.2.row.names) + read.simple.ssv(read.simple.ssv) --> column.2.row.names(column.2.row.names) + read.simple.csv(read.simple.csv) --> column.2.row.names(column.2.row.names) + write.simple.xlsx(write.simple.xlsx) --> construct.file.path(construct.file.path) + write.simple.xlsx(write.simple.xlsx) --> column.2.row.names(column.2.row.names) + write.simple.tsv(write.simple.tsv) --> construct.file.path(construct.file.path) + qs.2.table(qs.2.table) --> write.simple.xlsx(write.simple.xlsx) + qs.2.table(qs.2.table) --> write.simple.tsv(write.simple.tsv) +subgraph SubGraphOne + +end +``` +*created by `convert_igraph_to_mermaid()`* diff --git a/man/FirstCol2RowNames.Rd b/man/FirstCol2RowNames.Rd index 400fc21..ca62cfa 100644 --- a/man/FirstCol2RowNames.Rd +++ b/man/FirstCol2RowNames.Rd @@ -7,14 +7,14 @@ FirstCol2RowNames(Tibble, rownamecol = 1, make_names = FALSE, as.df = TRUE) } \arguments{ -\item{Tibble}{A dataframe without rownames (tibble style)} +\item{Tibble}{A data frame without row names (tibble style).} -\item{rownamecol}{rowname column, Default: 1} +\item{rownamecol}{Row name column. Default: 1.} -\item{make_names}{call make.names to remove weird characters, Default: FALSE} +\item{make_names}{Call \code{make.names} to remove unusual characters. Default: FALSE.} -\item{as.df}{Convert tibble to data frame? Default: TRUE} +\item{as.df}{Convert tibble to data frame? Default: TRUE.} } \description{ -Set First Col to Row Names +Set first column to row names. } diff --git a/man/FirstCol2RowNames.as.df.Rd b/man/FirstCol2RowNames.as.df.Rd index 6576e0e..072c335 100644 --- a/man/FirstCol2RowNames.as.df.Rd +++ b/man/FirstCol2RowNames.as.df.Rd @@ -7,12 +7,12 @@ FirstCol2RowNames.as.df(Tibble, rownamecol = 1, make_names = FALSE) } \arguments{ -\item{Tibble}{A dataframe without rownames (tibble style)} +\item{Tibble}{A data frame without row names (tibble style).} -\item{rownamecol}{rowname column, Default: 1} +\item{rownamecol}{Row name column. Default: 1.} -\item{make_names}{call make.names to remove weird characters, Default: FALSE} +\item{make_names}{Call \code{make.names} to remove unusual characters. Default: FALSE.} } \description{ -Set First Col to Row Names +Set first column to row names. } diff --git a/man/as.simple.md.table.Rd b/man/as.simple.md.table.Rd new file mode 100644 index 0000000..78227be --- /dev/null +++ b/man/as.simple.md.table.Rd @@ -0,0 +1,22 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ReadWriter.R +\name{as.simple.md.table} +\alias{as.simple.md.table} +\title{as.simple.md.table} +\usage{ +as.simple.md.table(input_df, row_names = TRUE, row_name_colname = "") +} +\arguments{ +\item{input_df}{Your data frame / matrix-like object.} + +\item{row_names}{Include row names as the first column? Default: TRUE.} + +\item{row_name_colname}{Column name for row names. Default: ''.} +} +\value{ +Character vector of Markdown lines. +} +\description{ +Convert a data.frame / matrix-like object to minimal GitHub-flavored Markdown +table lines (header, separator, body). Pure formatter; does not write to disk. +} diff --git a/man/column.2.row.names.Rd b/man/column.2.row.names.Rd index 346b6d2..8eefe01 100644 --- a/man/column.2.row.names.Rd +++ b/man/column.2.row.names.Rd @@ -15,8 +15,8 @@ column.2.row.names( ) } \arguments{ -\item{tibble}{A dataframe or tibble without row names. -Default: No default value, a dataframe must be provided.} +\item{tibble}{A data frame or tibble without row names. +Default: No default value; a data frame must be provided.} \item{rowname_column}{Index of the column to be used as row names. Default: 1.} @@ -24,18 +24,18 @@ Default: 1.} \item{make_names}{Boolean indicating whether to call \code{make.names} to sanitize row names. Default: FALSE.} -\item{as_df}{Boolean indicating whether to convert the input to a dataframe if it's not already one. +\item{as_df}{Boolean indicating whether to convert the input to a data frame if it's not already one. Default: TRUE.} -\item{warn}{Warn user if row names pre-exist. Default: TRUE.} +\item{warn}{Warn user if row names preexist. Default: TRUE.} \item{overwrite}{Overwrite row names if they already exist. Default: TRUE.} -\item{...}{Pass arguments to make.names()..} +\item{...}{Pass arguments to \code{make.names()}.} } \description{ -Converts the first column (or a specified column) of a dataframe or tibble into row names. -This function differs from \code{tibble::column_to_rownames} in that it takes column names or inices and -it offers the option to sanitize row names using \code{make.names}, provides a warning if there are -duplicated values in the row name column +Converts the first column (or a specified column) of a data frame or tibble into row names. +This function differs from \code{tibble::column_to_rownames} in that it takes column names or indices, +offers the option to sanitize row names using \code{make.names}, and provides a warning if there are +duplicated values in the row name column. } diff --git a/man/construct.file.path.Rd b/man/construct.file.path.Rd index d1e8e44..e1815c5 100644 --- a/man/construct.file.path.Rd +++ b/man/construct.file.path.Rd @@ -24,7 +24,7 @@ construct.file.path( \item{manual_directory}{An optional manual specification for the directory. Default: NULL.} -\item{v}{verbose Print path? Default: TRUE.} +\item{v}{Print path if verbose? Default: TRUE.} } \value{ A string representing the constructed file path. @@ -32,6 +32,7 @@ A string representing the constructed file path. \description{ Constructs a complete file path using either provided manual file name and directory or defaults to processing a given filename and using the current working directory. +At least one of \code{filename} or \code{manual_file_name} must be supplied. } \examples{ construct.file.path( diff --git a/man/convert.tsv.data.Rd b/man/convert.tsv.data.Rd index 47837e6..5877db0 100644 --- a/man/convert.tsv.data.Rd +++ b/man/convert.tsv.data.Rd @@ -7,15 +7,15 @@ convert.tsv.data(df_by_read.simple.tsv, digitz = 2, na_rep = 0) } \arguments{ -\item{df_by_read.simple.tsv}{Data frame (e.g. by read.simple.tsv).} +\item{df_by_read.simple.tsv}{Data frame (e.g., by \code{read.simple.tsv}).} -\item{digitz}{Number of digits when rounding up, Default: 2} +\item{digitz}{Number of digits when rounding up. Default: 2.} -\item{na_rep}{Replace NA?, Default: 0} +\item{na_rep}{Replace NA? Default: 0.} } \description{ -Fix NA issue in dataframes imported by the new read.simple.tsv. -Set na_rep to NA if you want to keep NA-s +Fix NA issues in data frames imported by the new read.simple.tsv. +Set \code{na_rep} to NA if you want to keep NAs. } \section{_________________________________________________________________________________________________}{ #' @title write.simple.xlsx.old diff --git a/man/qs.2.table.Rd b/man/qs.2.table.Rd index d6ae051..0a166b0 100644 --- a/man/qs.2.table.Rd +++ b/man/qs.2.table.Rd @@ -7,15 +7,15 @@ qs.2.table(path, out_file = c("tsv", "csv", "csv2", "excel")[1]) } \arguments{ -\item{path}{A character string specifying the path to the \code{.qs} file. Default: none.} +\item{path}{A character string specifying the path to the \code{.qs} file. Default: None.} \item{out_file}{A character string specifying the output file format. One of \code{"tsv"} (default), -\code{"csv"}, \code{"csv2"} (semicolon-separated), or \code{"excel"}. Default: \code{"tsv"}.} +\code{"csv"}, \code{"csv2"} (semicolon-separated), or \code{"excel"}.} } \value{ The function does not return a value but writes the file to disk in the specified format. } \description{ -This function reads in a \code{.qs} file and resaves it as either a \code{.tsv}, \code{.csv}, semicolon-separated +Reads in a \code{.qs} file and resaves it as either a \code{.tsv}, \code{.csv}, semicolon-separated \code{.csv} (csv2), or Excel file based on the \code{out_file} argument. } diff --git a/man/read.simple.Rd b/man/read.simple.Rd index 0b69864..4445d98 100644 --- a/man/read.simple.Rd +++ b/man/read.simple.Rd @@ -10,7 +10,7 @@ read.simple(...) \item{...}{Multiple simple variables to parse.} } \description{ -It is essentially read.table() with file/path parsing. +Essentially \code{read.table()} with file/path parsing. } \examples{ \dontrun{ diff --git a/man/read.simple.csv.Rd b/man/read.simple.csv.Rd index a6b1e5a..39928ee 100644 --- a/man/read.simple.csv.Rd +++ b/man/read.simple.csv.Rd @@ -17,21 +17,21 @@ read.simple.csv( \arguments{ \item{...}{Multiple simple variables to parse.} -\item{colnames}{Are there column names?, Default: TRUE} +\item{colnames}{Are there column names? Default: TRUE.} -\item{coltypes}{What type of variables are in columns? Auto-guessing can be very slow., Default: NULL} +\item{coltypes}{What type of variables are in columns? Auto-guessing can be very slow. Default: NULL.} -\item{wRownames}{With rownames?, Default: TRUE} +\item{wRownames}{With row names? Default: TRUE.} -\item{NaReplace}{Replace NA-values?, Default: TRUE} +\item{NaReplace}{Replace NA values? Default: TRUE.} -\item{asTibble}{Load as tibble or dataframe?, Default: FALSE (=load as df)} +\item{asTibble}{Load as tibble or data frame? Default: FALSE (load as data frame).} -\item{nmax}{Max number of rows to read, Default: Inf} +\item{nmax}{Max number of rows to read. Default: Inf.} } \description{ -Read in a file with excel style data: rownames in col1, -headers SHIFTED. The header should start with a TAB / First column name +Read in a file with Excel-style data: row names in column 1, +headers shifted. The header should start with a TAB; the first column name should be empty. } \examples{ diff --git a/man/read.simple.csv.named.vector.Rd b/man/read.simple.csv.named.vector.Rd index 34c63df..c827f03 100644 --- a/man/read.simple.csv.named.vector.Rd +++ b/man/read.simple.csv.named.vector.Rd @@ -16,22 +16,21 @@ read.simple.csv.named.vector( \arguments{ \item{file}{Path to the *.csv file.} -\item{sep}{Separator character, Default: ';' alternative: ','.} +\item{sep}{Separator character. Default: ';'; alternative: ','.} -\item{col_names}{Are there column names?, Default: TRUE} +\item{col_names}{Are there column names? Default: TRUE.} -\item{value_col}{Column number of the values in the input data frame. Default: 2} +\item{value_col}{Column number of the values in the input data frame. Default: 2.} -\item{name_col}{Column number of the names in the input data frame. Default: 1} +\item{name_col}{Column number of the names in the input data frame. Default: 1.} -\item{...}{Additional arguments passed to \code{\link[readr]{read_csv}} or read_csv2.} +\item{...}{Additional arguments passed to \code{\link[readr]{read_csv}} or \code{read_csv2}.} } \description{ -Read in a data frame (csv), and extact a value and a name column, and convert them -to a named vector. By default, it assumes the names in the first column and the values -excel style named vectors, names in col1, -headers SHIFTED. The header should start with a TAB / First column name -should be empty. +Read in a data frame (CSV), extract a value and a name column, and convert them +to a named vector. By default, it assumes the names are in the first column and the values in the second. +For Excel-style named vectors, names are in column 1 and headers are shifted. +The header should start with a TAB; the first column name should be empty. } \examples{ \dontrun{ diff --git a/man/read.simple.ssv.Rd b/man/read.simple.ssv.Rd index 86fa0c2..6b78a65 100644 --- a/man/read.simple.ssv.Rd +++ b/man/read.simple.ssv.Rd @@ -10,26 +10,29 @@ read.simple.ssv( colnames = TRUE, wRownames = TRUE, NaReplace = TRUE, - coltypes = NULL + coltypes = NULL, + asTibble = FALSE ) } \arguments{ \item{...}{Multiple simple variables to parse.} -\item{sep_}{Separator character, Default: ' '} +\item{sep_}{Separator character. Default: ' '.} -\item{colnames}{Are there column names?, Default: TRUE} +\item{colnames}{Are there column names? Default: TRUE.} -\item{wRownames}{With rownames?, Default: TRUE} +\item{wRownames}{With row names? Default: TRUE.} -\item{NaReplace}{Replace NA-values?, Default: TRUE} +\item{NaReplace}{Replace NA values? Default: TRUE.} -\item{coltypes}{What type of variables are in columns? Auto-guessing can be very slow., Default: NULL} +\item{coltypes}{What type of variables are in columns? Auto-guessing can be very slow. Default: NULL.} + +\item{asTibble}{Load as tibble or data frame? Default: FALSE (load as data frame).} } \description{ -Space separeted values. Read in a file with excel style data: -rownames in col1, headers SHIFTED. The header should start with a -TAB / First column name should be empty. +Space separated values. Read in a file with Excel-style data: +row names in column 1, headers shifted. The header should start with a +TAB; the first column name should be empty. } \examples{ \dontrun{ diff --git a/man/read.simple.table.Rd b/man/read.simple.table.Rd index a760740..f441414 100644 --- a/man/read.simple.table.Rd +++ b/man/read.simple.table.Rd @@ -9,14 +9,14 @@ read.simple.table(..., colnames = TRUE, coltypes = NULL) \arguments{ \item{...}{Multiple simple variables to parse.} -\item{colnames}{Are there column names? Default: TRUE} +\item{colnames}{Are there column names? Default: TRUE.} -\item{coltypes}{What type of variables are in columns? Auto-guessing can be very slow. Default: NULL} +\item{coltypes}{What type of variables are in columns? Auto-guessing can be very slow. Default: NULL.} } \description{ -Read in a file. default: header defines colnames, no rownames. -For rownames give the col nr. with rownames, eg. 1 The header should start -with a TAB / First column name should be empty. +Read a file. Default: header defines column names, no row names. +For row names give the column number with row names, e.g., 1. The header should start +with a TAB; the first column name should be empty. } \examples{ \dontrun{ diff --git a/man/read.simple.tsv.Rd b/man/read.simple.tsv.Rd index b9a6029..87981d0 100644 --- a/man/read.simple.tsv.Rd +++ b/man/read.simple.tsv.Rd @@ -17,21 +17,21 @@ read.simple.tsv( \arguments{ \item{...}{Multiple simple variables to parse.} -\item{sep_}{Separator character, Default: ' '} +\item{sep_}{Separator character. Default: '\\t'.} -\item{colnames}{Are there column names?, Default: TRUE} +\item{colnames}{Are there column names? Default: TRUE.} -\item{wRownames}{With rownames?, Default: TRUE} +\item{wRownames}{With row names? Default: TRUE.} -\item{coltypes}{What type of variables are in columns? Auto-guessing can be very slow., Default: NULL} +\item{coltypes}{What type of variables are in columns? Auto-guessing can be very slow. Default: NULL.} -\item{NaReplace}{Replace NA-values?, Default: TRUE} +\item{NaReplace}{Replace NA values? Default: TRUE.} -\item{asTibble}{Load as tibble or dataframe?, Default: FALSE (=load as df)} +\item{asTibble}{Load as tibble or data frame? Default: FALSE (load as data frame).} } \description{ -Read in a file with excel style data: rownames in col1, -headers SHIFTED. The header should start with a TAB / First column name +Read in a file with Excel-style data: row names in column 1, +headers shifted. The header should start with a TAB; the first column name should be empty. } \examples{ diff --git a/man/read.simple.tsv.named.vector.Rd b/man/read.simple.tsv.named.vector.Rd index eeb65dc..8cf3800 100644 --- a/man/read.simple.tsv.named.vector.Rd +++ b/man/read.simple.tsv.named.vector.Rd @@ -10,8 +10,8 @@ read.simple.tsv.named.vector(...) \item{...}{Multiple simple variables to parse.} } \description{ -Read in a file with excel style named vectors, names in col1, -headers SHIFTED. The header should start with a TAB / First column name +Read in a file with Excel-style named vectors, names in column 1, +headers shifted. The header should start with a TAB; the first column name should be empty. } \examples{ diff --git a/man/read.simple.vec.Rd b/man/read.simple.vec.Rd index d67c14c..f4994c6 100644 --- a/man/read.simple.vec.Rd +++ b/man/read.simple.vec.Rd @@ -10,9 +10,7 @@ read.simple.vec(...) \item{...}{Multiple simple variables to parse.} } \description{ -read.simple.vec - -Read each line of a file to an element of a vector (read in new-line separated values, no header!). +Read each line of a file to an element of a vector (read in newline-separated values, no header!). } \examples{ \dontrun{ diff --git a/man/read.simple.xls.Rd b/man/read.simple.xls.Rd index 4ebe19b..1663ee1 100644 --- a/man/read.simple.xls.Rd +++ b/man/read.simple.xls.Rd @@ -13,19 +13,19 @@ read.simple.xls( ) } \arguments{ -\item{pfn}{Path and File name, Default: kollapse(...)} +\item{pfn}{Path and file name. Default: kollapse(...).} -\item{row_namePos}{Where is the rowname, Default: NULL} +\item{row_namePos}{Where is the row name? Default: NULL.} \item{...}{Multiple simple variables to parse.} -\item{header_}{Is there header? Default: TRUE} +\item{header_}{Is there a header? Default: TRUE.} -\item{WhichSheets}{Which sheets to read in} +\item{WhichSheets}{Which sheets to read.} } \description{ -Read multi-sheet excel files. row_namePos = NULL for automatic -names Look into: http://readxl.tidyverse.org/. +Read multi-sheet Excel files. \code{row_namePos = NULL} for automatic +names. See http://readxl.tidyverse.org/. } \examples{ \dontrun{ diff --git a/man/read.simple.xlsx.Rd b/man/read.simple.xlsx.Rd index d3af674..5dc7629 100644 --- a/man/read.simple.xlsx.Rd +++ b/man/read.simple.xlsx.Rd @@ -23,19 +23,19 @@ Default: All sheets.} \item{col_names}{Logical, whether to use the first row as column names. Default: TRUE.} -\item{row_names}{Numeric, whether to convert a column to row names. -Default: 1. Use 0 for no conversion. Default: FALSE.} +\item{row_names}{Numeric indicating which column to convert to row names. +Use 0 or FALSE for no conversion. Default: FALSE.} -\item{trim_ws}{Logical, whether to trim white spaces from column names.} +\item{trim_ws}{Logical, whether to trim whitespace from column names.} -\item{...}{Pass arguments to read.xlsx().} +\item{...}{Pass arguments to \code{read.xlsx()}.} } \value{ A list of data frames, each representing a sheet from the XLSX file. } \description{ Reads specified sheets from an XLSX file into a list of data frames. -It allows customization of column names, row names, and trimming of white spaces. +It allows customization of column names, row names, and trimming of whitespace. } \seealso{ \code{\link[openxlsx]{read.xlsx}} diff --git a/man/write.simple.Rd b/man/write.simple.Rd index e430eaa..8cc16bd 100644 --- a/man/write.simple.Rd +++ b/man/write.simple.Rd @@ -30,7 +30,7 @@ write.simple( \item{o}{If TRUE, opens the file after writing on OS X using 'system(open ...)'. Default: FALSE.} -\item{v}{verbose Print path? Default: TRUE.} +\item{v}{Print path if verbose? Default: TRUE.} } \value{ Outputs a .tsv file and optionally prints the length of the input data frame. diff --git a/man/write.simple.append.Rd b/man/write.simple.append.Rd index 818e9ae..c254cf7 100644 --- a/man/write.simple.append.Rd +++ b/man/write.simple.append.Rd @@ -30,7 +30,7 @@ write.simple.append( \item{o}{If TRUE, opens the file after writing on OS X using 'system(open ...)'. Default: FALSE.} -\item{v}{verbose Print path? Default: TRUE.} +\item{v}{Print path if verbose? Default: TRUE.} } \value{ Appends data to an existing .tsv file. diff --git a/man/write.simple.md.table.Rd b/man/write.simple.md.table.Rd new file mode 100644 index 0000000..6193540 --- /dev/null +++ b/man/write.simple.md.table.Rd @@ -0,0 +1,58 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ReadWriter.R +\name{write.simple.md.table} +\alias{write.simple.md.table} +\title{write.simple.md.table} +\usage{ +write.simple.md.table( + input_df, + extension = "md", + filename = substitute(input_df), + suffix = NULL, + manual_file_name = NULL, + manual_directory = NULL, + row_names = TRUE, + row_name_colname = "", + o = FALSE, + v = TRUE, + ... +) +} +\arguments{ +\item{input_df}{Your data frame / matrix-like object.} + +\item{extension}{File extension. Default: 'md'.} + +\item{filename}{The base name for the output file. Default: Name of the input data frame.} + +\item{suffix}{A suffix added to the filename. Default: NULL.} + +\item{manual_file_name}{Specify full filename if you do not want to name it after the variable.} + +\item{manual_directory}{Specify the directory where the file should be saved.} + +\item{row_names}{Include row names as the first column? Default: TRUE.} + +\item{row_name_colname}{Column name for row names. Default: ''.} + +\item{o}{Open the file after saving? Default: FALSE.} + +\item{v}{Print path if verbose? Default: TRUE.} + +\item{...}{Additional arguments passed to the kollapse() function used for the file name.} +} +\description{ +Write an R data.frame / matrix-like object to disk as a minimal GitHub-flavored +Markdown table (.md). +} +\examples{ +df <- data.frame( + Name = c("Alice", "Bob | The Builder", NA, "Eve\nNewline"), + Age = c(30, 25, 28, NA), + Note = c("Loves R\\\\Markdown", "Enjoys building\tthings", "No special chars", "Line1\r\nLine2"), + stringsAsFactors = FALSE, + check.names = FALSE +) +write.simple.md.table(df, manual_file_name = "example_table.md", row_names = TRUE) + +} diff --git a/man/write.simple.tsv.Rd b/man/write.simple.tsv.Rd index ccfcaa6..11f20b2 100644 --- a/man/write.simple.tsv.Rd +++ b/man/write.simple.tsv.Rd @@ -21,39 +21,40 @@ write.simple.tsv( ) } \arguments{ -\item{input_df}{Your Dataframe with row- and column-names} +\item{input_df}{Your data frame with row and column names.} -\item{separator}{Field separator, such as "," for csv} +\item{separator}{Field separator, such as ',' for CSV.} -\item{extension}{e.g.: tsv} +\item{extension}{e.g., 'tsv'.} -\item{filename}{The base name for the output file. Default: Name of the input vector.} +\item{filename}{The base name for the output file. Default: Name of the input data frame.} -\item{suffix}{A suffix added to the filename, Default: NULL} +\item{suffix}{A suffix added to the filename. Default: NULL.} -\item{manual_file_name}{Specify full filename if you do not want to name it by the variable name.} +\item{manual_file_name}{Specify full filename if you do not want to name it after the variable.} \item{manual_directory}{Specify the directory where the file should be saved.} -\item{row_names}{Write row names? TRUE by default} +\item{row_names}{Write row names? Default: TRUE.} -\item{col_names}{Write column names? NA by default, TRUE if row_names == FALSE} +\item{col_names}{Write column names? Default: NA, set to TRUE if \code{row_names == FALSE}.} -\item{gzip}{Compress the file after saving? FALSE by default} +\item{gzip}{Compress the file after saving? Default: FALSE.} -\item{o}{Open the file after saving? FALSE by default} +\item{o}{Open the file after saving? Default: FALSE.} -\item{v}{verbose Print path? Default: TRUE.} +\item{v}{Print path if verbose? Default: TRUE.} -\item{...}{Additional arguments passed to write.table()} +\item{...}{Additional arguments passed to the kollapse() function used for the file name and to \code{write.table()}.} } \description{ -Write out a matrix-like R-object WITH ROW- AND COLUMN- NAMES to a file with as tab separated -values (.tsv). Your output filename will be either the variable's name. The output file will be -located in "OutDir" specified by you at the beginning of the script, or under your current -working directory. You can pass the PATH and VARIABLE separately (in order), they will be -concatenated to the filename. If col.names = NA and row.names = TRUE a blank column name is added, +Write out a matrix-like R object with row and column names to a file as tab-separated +values (.tsv). The output filename will be either the variable's name or the one you provide. The output +file will be located in the directory specified at the beginning of the script or in your current +working directory. You can pass the path and variable separately (in order); they will be concatenated +to the filename. If \code{col.names = NA} and \code{row.names = TRUE}, a blank column name is added, which is the convention used for CSV files to be read by spreadsheets. +It can also write CSV files if you set the separator to ',' or ';'. } \examples{ YourDataFrameWithRowAndColumnNames <- cbind("A" = rnorm(100), "B" = rpois(100, 8)) diff --git a/man/write.simple.vec.Rd b/man/write.simple.vec.Rd index d42e5af..ebb1d9a 100644 --- a/man/write.simple.vec.Rd +++ b/man/write.simple.vec.Rd @@ -12,7 +12,8 @@ write.simple.vec( manual_file_name = NULL, manual_directory = NULL, o = FALSE, - v = TRUE + v = TRUE, + make_names = TRUE ) } \arguments{ @@ -30,13 +31,16 @@ write.simple.vec( \item{o}{If TRUE, opens the file after writing on OS X using 'system(open ...)'. Default: FALSE.} -\item{v}{verbose Print path? Default: TRUE.} +\item{v}{Print path if verbose? Default: TRUE.} + +\item{make_names}{If TRUE, applies \code{make.names} to the filename. Generally safer, but it can, +e.g.: inadvarently change "_myFile" to "X_myFile". Default: TRUE.} } \value{ Outputs a .vec file and optionally prints the length of the input vector. } \description{ -Writes a vector-like R object to a file as newline separated values (.vec). +Writes a vector-like R object to a file as newline-separated values (.vec). The output filename can be auto-generated from the variable's name or manually specified. The file is saved in the specified output directory or the current working directory. The path and variable name can be passed separately and will be concatenated to form the filename. diff --git a/man/write.simple.xlsx.Rd b/man/write.simple.xlsx.Rd index 3560794..7f70601 100644 --- a/man/write.simple.xlsx.Rd +++ b/man/write.simple.xlsx.Rd @@ -20,18 +20,19 @@ write.simple.xlsx( has_row_names = TRUE, FreezeFirstRow = TRUE, FreezeFirstCol = FALSE, - v = TRUE + v = TRUE, + gzip = FALSE ) } \arguments{ \item{named_list}{A list of data frames or matrices to write out. -Default: No default value, a list must be provided.} +Default: No default value; a list must be provided.} \item{rowname_column}{The column name or index to use as row names in the Excel file. -Required, no default value.} +Default: 1.} \item{filename}{The base name for the output file, derived from the 'named_list' variable if not specified. -Default: Derived using 'substitute(named_list)'.} +Default: Derived using \code{substitute(named_list)}.} \item{suffix}{A suffix to be added to the output filename. Default: NULL.} @@ -53,13 +54,15 @@ Default: FALSE.} \item{HeaderCharStyle}{Character style for the header (e.g., 'bold', 'italic', 'underline'). Default: 'bold'.} -\item{has_row_names}{Logical; if set to FALSE, converts the first column to row names. Default: TRUE} +\item{has_row_names}{Logical; if set to FALSE, converts the first column to row names. Default: TRUE.} \item{FreezeFirstRow}{Logical; if TRUE, freezes the first row in Excel. Default: TRUE.} \item{FreezeFirstCol}{Logical; if TRUE, freezes the first column in Excel. Default: FALSE.} -\item{v}{verbose Print path? Default: TRUE.} +\item{v}{Print path if verbose? Default: TRUE.} + +\item{gzip}{Compress the file after saving? Default: FALSE.} } \description{ Write out a list of matrices or data frames with row and column names diff --git a/man/write.simplest.Rd b/man/write.simplest.Rd index 4efc173..737e6a4 100644 --- a/man/write.simplest.Rd +++ b/man/write.simplest.Rd @@ -2,14 +2,14 @@ % Please edit documentation in R/ReadWriter.R \name{write.simplest} \alias{write.simplest} -\title{Append or write a vector to standard file, one element per line.} +\title{Append or write a vector to a standard file, one element per line.} \usage{ write.simplest( vec = LETTERS[1:11], append = TRUE, header = NULL, prefix = kppws(substitute(vec), idate()), - file_path = "/groups/knoblich/Projects/connectomics/Analysis/__clipboard.txt" + file_path = get0("path_write_simplest", ifnotfound = "./__clipboard.txt") ) } \arguments{ @@ -22,13 +22,13 @@ write.simplest( \item{prefix}{A prefix to the header. Default: \code{kppws(substitute(vec), idate())}.} \item{file_path}{A string specifying the file path where the vector will be written. Default: -\code{"/groups/knoblich/Projects/connectomics/Analysis/__clipboard.txt"}.} +path stored in \code{path_write_simplest} global variable, otherwise \code{"./__clipboard.txt"}.} } \value{ A message indicating the length of the vector and the file path to which it was written. } \description{ -Alternative to clipboard. This function takes a vector and appends it +Alternative to the clipboard. This function takes a vector and appends it to a specified file. } \examples{