Skip to content

Instantly share code, notes, and snippets.

@zkamvar
Created April 27, 2014 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zkamvar/11338685 to your computer and use it in GitHub Desktop.
Save zkamvar/11338685 to your computer and use it in GitHub Desktop.
Insert a separator into a character vector containing two pieces of information where one piece has a constant width.
#==============================================================================#
# insert_sep.r Insert a separator into a character vector containing two pieces
# of information where one piece has a constant width.
#
# Author: Zhian N. Kamvar
# License: GPLv3
# Year: 2014
# Waranty: NONE
#
# Arguments:
# string = a character vector
# sep = a character defining the separator.
# at = the length of the fixed width information.
# forward = if TRUE, the fixed width information appears first. If FALSE, it
# appears second.
#==============================================================================#
insert_sep <- function(string, sep = "_", at = 2, forward = TRUE){
string_lengths <- nchar(string)
if (!forward){
at <- string_lengths - at
}
prefix <- substr(string, 1, at)
suffix <- substr(string, at + 1, string_lengths)
out_strings <- paste(prefix, suffix, sep = sep)
return(out_strings)
}
# Generate data
forward <- vapply(1:length(letters), function(x) paste0(paste0(sample(LETTERS, 2), collapse = ""), sample(c("2000", "unknown"), 1, prob = c(0.9, 0.1))), character(1))
reverse <- vapply(1:length(letters), function(x) paste0(sample(c("2000", "unknown"), 1, prob = c(0.9, 0.1)), paste0(sample(LETTERS, 2), collapse = "")), character(1))
# Test
insert_sep(forward)
insert_sep(reverse, forward = FALSE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment