hacker

Tricks and Convenience functions for GNU R
Log | Files | Refs

commit f718a851fd433e21e03a403ea254a42910ee1ffb
Author: JayVii <jayvii@posteo.de>
Date:   Wed,  2 Sep 2020 12:44:37 +0200

sub preload

Diffstat:
Asub_preload.R | 43+++++++++++++++++++++++++++++++++++++++++++
1 file changed, 43 insertions(+), 0 deletions(-)

diff --git a/sub_preload.R b/sub_preload.R @@ -0,0 +1,43 @@ +# Copyright (C) 2020 Jan "JayVii" +# Author 2020 Jan "JayVii" <jayvii@posteo.de> +# SPDX-License-Identifier: gpl-3.0 +# About this header: <https://reuse.software> + +# Apply regex-functions prior to loading a data set (.txt, .csv, ...) +# A direct substitute for sub() and gsub() if data has not been loaded into RAM +# yet. + +sub_preload <- function(pattern, replacement, file, backup = TRUE, + global = FALSE, extended = TRUE) { + + # Check supported OS + supported_plattforms <- c("Linux") + if (!(Sys.info()[["sysname"]] %in% supported_plattforms)) { + stop("Sorry, your OS is currently not supported...") + } + + # Check whether sed is installed + sed_path <- system2(command = "whereis", args = "sed | awk '{ print $2 }'", + stdout = TRUE) + if (nchar(sed_path) < 1) { + stop("This function requires GNU sed, please install it on the host", + " system and try again...") + } + + # initialize additional parameters (empty characters) + gl <- ipost <- eext <- "" + + # Construct sed script command + if (global) gl <- "g" + script <- paste0("s/", pattern, "/", replacement, "/", gl) + + # Construct additional parameters + if (backup) ipost <- "=.BAK" + if (extended) eext <- "-E" + args <- paste0("--in-place", ipost, " ", eext, " ", "-e") + + # run sed + system2(command = "sed", args = paste(args, script, file), stdout = "") +} + +# EOF sub_preload.R