R/pipe_functions.R

Defines functions exec_if pipeMarker createMap ifel_repl returnPart cleanNames

Documented in cleanNames createMap exec_if ifel_repl pipeMarker returnPart

#' Cleans up names of imported data frames
#'
#' @return data.frame
#'
#' @examples
#' cleanNames(data)
#'
#' @export
cleanNames <- function(x){
	names(x) <- names(x) %>%
		iconv("UTF-8", "UTF-8", sub="") %>%
		gsub(pattern="\\.", replacement=" ") %>%
		trimall() %>%
		gsub(pattern=" +", replacement="_") %>%
		tolower()
	return(x)
}

#' functional way of returning specific part of data object
#'
#' @return Any
#'
#' @examples
#' returnPart(data, objectName)
#'
#' @export
returnPart <- function(x, y){
	eval(parse(text=sprintf("x$`%s`", y)))
}


#' Replaces values based on if/else boolean logic.
#' supports piping
#'
#' @return Vector
#'
#' @examples
#' c("a","b", "x", "x", "a") %>% ifel_repl(. == "x", "replaced!")
#'
#' @export
ifel_repl <- function(x, boolean, replacement){
	ifelse(boolean, replacement, x)
}


#' Creates a mapping vector based on data.frame columns
#' supports piping a la dplyr
#'
#' @return Vector
#'
#'
#' @export
createMap <- function(x, base, name){
    x[,base] %>%
        c() %>%
        setNames(x[,name])
}

#' Prints something then passes object along
#' Text marker for long piped processes
#'
#' @return Anything
#'
#'
#' @export
pipeMarker <- function(x, text=x){
    cat(text, fill=TRUE)
    return(x)
}


#' Execute If
#'
#' This function executes a function upon an object if condition are met.
#' @export
#'
#' @examples
#' x %>%
#' 	exec_if(TRUE, ~mutate(.x, foo="bar"))
#'
#'

exec_if <- function(x, cond, .f){
	require(purrr)
	if(cond){
		exec(as_mapper(.f), x, environment())
	} else{
		return(x)
	}
}
Gimperion/tomkit documentation built on May 22, 2020, 12:14 a.m.