├── man ├── getOS.Rd ├── na2zero.Rd ├── unlibrary.Rd ├── mymode.Rd ├── read_textfile.Rd ├── table_sorted.Rd ├── toinitialcap.Rd ├── getpres.Rd ├── na2zero2.Rd ├── varname2string.Rd ├── number_with_commas.Rd ├── write_textfile.Rd ├── edit_project_list.Rd ├── copy_textfile_to_clipboard.Rd ├── string2varname.Rd ├── getparty.Rd ├── grapes-ni-grapes.Rd ├── setindex_bygroup.Rd ├── removecolsAllNA.Rd ├── renamecol.Rd ├── strings_to_ordered_factors.Rd ├── vector_to_single_string_w_linebreaks.Rd ├── rollingavg.Rd ├── add_row.Rd ├── maxn.Rd ├── add_row_from_list.Rd ├── streaks.Rd ├── elec_pcts_by_row.Rd ├── add_pct_cols_to_dataframe.Rd └── elec_find_winner.Rd ├── R ├── catsincolumn.R ├── ni.R ├── numberswithcommas.R ├── stats.R ├── factors.R ├── renamecol.R ├── removecolsAllNA.R ├── edit_project_file.R ├── maxn.R ├── rollingavg.R ├── streaks.R ├── elect_pcts_by_row.R ├── add_row.R ├── add_row_from_list.R ├── add_pct_cols_to_dataframe.R ├── elec_find_winner.R ├── strings.R ├── getpres.R └── misc.R ├── DESCRIPTION ├── NAMESPACE ├── README.md └── README.Rmd /man/getOS.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{getOS} 4 | \alias{getOS} 5 | \title{getOS} 6 | \usage{ 7 | getOS() 8 | } 9 | \description{ 10 | Wrapper to see what operating system is running 11 | } 12 | \examples{ 13 | getOS() 14 | 15 | } 16 | \keyword{environment} 17 | -------------------------------------------------------------------------------- /man/na2zero.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{na2zero} 4 | \alias{na2zero} 5 | \title{na2zero} 6 | \usage{ 7 | na2zero(mydf) 8 | } 9 | \arguments{ 10 | \item{mydf}{a data frame} 11 | } 12 | \description{ 13 | Turn all the NA values in a data frame to zero. 14 | } 15 | \examples{ 16 | newdf <- na2zero(mydf) 17 | 18 | } 19 | -------------------------------------------------------------------------------- /man/unlibrary.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{unlibrary} 4 | \alias{unlibrary} 5 | \title{unlibrary} 6 | \usage{ 7 | unlibrary(pkgname) 8 | } 9 | \arguments{ 10 | \item{pkgname}{name of a package as a character string in quotation marks} 11 | } 12 | \description{ 13 | Opposite of library - wrapper to detach a package 14 | } 15 | \examples{ 16 | unlibrary(devtools) 17 | 18 | } 19 | \keyword{environment} 20 | -------------------------------------------------------------------------------- /R/catsincolumn.R: -------------------------------------------------------------------------------- 1 | 2 | catsincols <- function(mydata, colhasheader, colhasvalue, catcol="category"){ 3 | if(!require(tidyr)){install.packages("tidyr")} 4 | orignames <- names(mydata) 5 | newnames <- c(orignames, catcol) 6 | for(i in 1:nrow(mydata)){ 7 | mydata$newcat[i] <- ifelse(is.na(mydata[[colhasvalue]][i]), mydata[[colhasheader]][i], NA) 8 | } 9 | mydata <- mydata %>% 10 | fill(newcat) 11 | names(mydata) <- newnames 12 | return(mydata) 13 | } 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /man/mymode.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/stats.R 3 | \name{mymode} 4 | \alias{mymode} 5 | \title{mymode} 6 | \usage{ 7 | mymode(myvector) 8 | } 9 | \arguments{ 10 | \item{myvector}{a vector} 11 | } 12 | \description{ 13 | Get the statistical mode from a vector of values. 14 | } 15 | \examples{ 16 | salaries <- c(32000, 40000, 12000, 12000, 12000, 12000, 12000, 35000, 90000, 100000, 1000000) 17 | themode <- mymode(salaries) 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /man/read_textfile.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{read_textfile} 4 | \alias{read_textfile} 5 | \title{read_textfile} 6 | \usage{ 7 | read_textfile(filename) 8 | } 9 | \arguments{ 10 | \item{filename}{name of a file as a character string in quotation marks} 11 | } 12 | \description{ 13 | Read a text file into a variable as a single character string 14 | } 15 | \examples{ 16 | mystring <- read_textfile("myfile.txt") 17 | 18 | } 19 | -------------------------------------------------------------------------------- /man/table_sorted.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{table_sorted} 4 | \alias{table_sorted} 5 | \title{table_sorted} 6 | \usage{ 7 | table_sorted(myvector) 8 | } 9 | \description{ 10 | Get a frequency table from a vector of categorical variables sorted by frequency in descending order 11 | } 12 | \examples{ 13 | myvec <- c("white", "blue", "purple", "white", "blue", "blue", "blue", "purple", "yellow", "white") 14 | table_sorted(myvec) 15 | } 16 | -------------------------------------------------------------------------------- /R/ni.R: -------------------------------------------------------------------------------- 1 | #' "Not in" function 2 | #' 3 | #' Base R has the \%in\% function to create a logical vector whether one object is contained within another object. 4 | #' Why not \%ni\% to get a logical vector if one object is NOT contained within another? 5 | #' Idea from stackoverflow 6 | #' http://stackoverflow.com/questions/11302985/match-with-negation 7 | #' 8 | #' @param myobject a vector 9 | #' @keywords function 10 | #' @export 11 | #' @examples 12 | #' 5 %ni% c(2,4,6) 13 | #' # TRUE 14 | #' 15 | '%ni%' <- Negate('%in%') 16 | 17 | 18 | -------------------------------------------------------------------------------- /man/toinitialcap.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/strings.R 3 | \name{toinitialcap} 4 | \alias{toinitialcap} 5 | \title{toinitialcap} 6 | \usage{ 7 | toinitialcap(mystring) 8 | } 9 | \arguments{ 10 | \item{mystring}{(any string)} 11 | } 12 | \description{ 13 | Base R has toupper and tolower - why not toinitialcap? 14 | This renames the example .simpleCap function in the toupper help file. 15 | } 16 | \examples{ 17 | toinitialcap("this is a headline") 18 | } 19 | \keyword{strings} 20 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: rmiscutils 2 | Type: Package 3 | Title: Collection of Misc R Functions I've Found useful Over the Years 4 | Version: 0.2 5 | Date: 2015-03-01 6 | Author: c( person("Sharon", "Machlis", , "smachlis@computerworld.com", c("aut", 7 | "cre")), ) 8 | Description: This package is a collection of miscellaneous R functions I've 9 | either found or written over the years that I've found helpful. 10 | License: GPL-3 11 | LazyData: TRUE 12 | RoxygenNote: 6.1.1 13 | Imports: rio, 14 | readr, 15 | usethis 16 | -------------------------------------------------------------------------------- /R/numberswithcommas.R: -------------------------------------------------------------------------------- 1 | #' numbers_with_commas 2 | #' 3 | #' Turn a number with commas, which R views as a string, into a numeric class number. Will also remove dollar signs. 4 | #' @param mynumstring - one or more character strings such as "3,650" 5 | #' @export 6 | #' @examples 7 | #' vect <- c("3,567", "465", "$4,000,654") 8 | #' number_with_commas(vect) 9 | #' # [1] 3567 465 4000654 10 | 11 | 12 | number_with_commas <- function(mynumstring){ 13 | x <- gsub(",", "", mynumstring) 14 | x <- gsub("\\$", "", x) 15 | myanswer <- as.numeric(x) 16 | return(myanswer) 17 | } 18 | 19 | 20 | -------------------------------------------------------------------------------- /man/getpres.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getpres.R 3 | \name{getpres} 4 | \alias{getpres} 5 | \title{Get US President by Date} 6 | \usage{ 7 | getpres(thedate) 8 | } 9 | \arguments{ 10 | \item{thedate}{Any date on or after 1945-04-12 as an R Date object.} 11 | } 12 | \description{ 13 | Get the name of US president on a given date starting with Harry Truman. 14 | } 15 | \details{ 16 | Input a date object on or after 1945-04-12 and get the name of the US president who was in office at that time. 17 | } 18 | \examples{ 19 | getpres(as.Date("2000-01-01")) 20 | } 21 | -------------------------------------------------------------------------------- /man/na2zero2.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{na2zero2} 4 | \alias{na2zero2} 5 | \title{na2zero2} 6 | \usage{ 7 | na2zero2(mydf) 8 | } 9 | \arguments{ 10 | \item{mydf}{a data frame} 11 | } 12 | \description{ 13 | Turn all the NA values in a data frame to zero but only in columns that are numeric or integers. Uses for loops, so may be slow for large data frames. 14 | } 15 | \examples{ 16 | 17 | x1 <- c(5,7,NA,9,10) 18 | x2 <- c(2.4, 7, 6.4, NA,5.2) 19 | x3 <- c(NA, "A", "B", "C", "D") 20 | x <- data.frame(x1,x2,x3) 21 | newdf <- na2zero2(x) 22 | 23 | } 24 | -------------------------------------------------------------------------------- /man/varname2string.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/strings.R 3 | \name{varname2string} 4 | \alias{varname2string} 5 | \title{varname2string} 6 | \usage{ 7 | varname2string(x) 8 | } 9 | \arguments{ 10 | \item{x}{variable name} 11 | } 12 | \value{ 13 | string 14 | } 15 | \description{ 16 | This function takes a variable name and turns it into a string. 17 | Code from John Ramey at http://johnramey.net/blog/2010/12/28/converting-a-string-to-a-variable-name-on-the-fly-and-vice-versa-in-r/ 18 | } 19 | \examples{ 20 | x <- 42 21 | varname2string(x) 22 | # [1] "x" 23 | 24 | } 25 | -------------------------------------------------------------------------------- /R/stats.R: -------------------------------------------------------------------------------- 1 | #' mymode 2 | #' 3 | #' Get the statistical mode from a vector of values. 4 | #' 5 | #' @export 6 | #' @param myvector a vector 7 | #' @examples 8 | #' salaries <- c(32000, 40000, 12000, 12000, 12000, 12000, 12000, 35000, 90000, 100000, 1000000) 9 | #' themode <- mymode(salaries) 10 | #' 11 | #' 12 | mymode <- function(myvector){ 13 | freqs <- sort(table(myvector)) 14 | results <- names(freqs[freqs == max(freqs)]) 15 | if(is.numeric(myvector[1])){ 16 | results <- as.numeric(results) 17 | } 18 | if(is.integer(myvector[1])){ 19 | results <- as.integer(results) 20 | } 21 | return(results) 22 | } 23 | -------------------------------------------------------------------------------- /man/number_with_commas.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/numberswithcommas.R 3 | \name{number_with_commas} 4 | \alias{number_with_commas} 5 | \title{numbers_with_commas} 6 | \usage{ 7 | number_with_commas(mynumstring) 8 | } 9 | \arguments{ 10 | \item{mynumstring}{- one or more character strings such as "3,650"} 11 | } 12 | \description{ 13 | Turn a number with commas, which R views as a string, into a numeric class number. Will also remove dollar signs. 14 | } 15 | \examples{ 16 | vect <- c("3,567", "465", "$4,000,654") 17 | number_with_commas(vect) 18 | # [1] 3567 465 4000654 19 | } 20 | -------------------------------------------------------------------------------- /man/write_textfile.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{write_textfile} 4 | \alias{write_textfile} 5 | \title{write_textfile} 6 | \usage{ 7 | write_textfile(myvar, myfilename) 8 | } 9 | \arguments{ 10 | \item{myvar}{Variable that holds character string data} 11 | 12 | \item{myfilename}{string Name of the file} 13 | } 14 | \description{ 15 | Write a variable with one or more character strings to a text file taken from this stackoverflow answer http://stackoverflow.com/a/2470277/718150 16 | } 17 | \examples{ 18 | \dontrun{ 19 | write_textfile(mydata, "myfile.txt") 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /man/edit_project_list.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/edit_project_file.R 3 | \name{edit_project_list} 4 | \alias{edit_project_list} 5 | \title{Open file to edit RStudio project list} 6 | \usage{ 7 | edit_project_list(windrive = "C") 8 | } 9 | \arguments{ 10 | \item{windrive}{For Windows only, drive where RStudio is installed. Defaults to C.} 11 | } 12 | \value{ 13 | action opens file 14 | } 15 | \description{ 16 | Opens file for editing the RStudio dropdown project list so individual projects can be removed from the list. 17 | } 18 | \examples{ 19 | \dontrun{ 20 | edit_project_list() 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /man/copy_textfile_to_clipboard.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/strings.R 3 | \name{copy_textfile_to_clipboard} 4 | \alias{copy_textfile_to_clipboard} 5 | \title{copy_textfile_to_clipboard} 6 | \usage{ 7 | copy_textfile_to_clipboard(mytextfile) 8 | } 9 | \arguments{ 10 | \item{mytextfile}{Path to a text file as a character string} 11 | } 12 | \description{ 13 | This function takes the path to a textfile as a character string and reads it into the Windows or Mac clipboards only. 14 | } 15 | \examples{ 16 | myfile <- "data/textfile.txt" 17 | copy_textfile_to_clipboard(myfile) 18 | } 19 | \keyword{clipboard} 20 | -------------------------------------------------------------------------------- /man/string2varname.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/strings.R 3 | \name{string2varname} 4 | \alias{string2varname} 5 | \title{string2varname} 6 | \usage{ 7 | string2varname(x) 8 | } 9 | \arguments{ 10 | \item{x}{string} 11 | } 12 | \value{ 13 | value of variable with name equal to the string 14 | } 15 | \description{ 16 | This function takes a string and turns it into a variable name. 17 | Code from John Ramey at http://johnramey.net/blog/2010/12/28/converting-a-string-to-a-variable-name-on-the-fly-and-vice-versa-in-r/ 18 | } 19 | \examples{ 20 | x <- 42 21 | eval(parse(text = "x")) 22 | # [1] 42 23 | 24 | } 25 | -------------------------------------------------------------------------------- /R/factors.R: -------------------------------------------------------------------------------- 1 | #' strings_to_ordered_factors 2 | #' 3 | #' Turn a vector of strings into a factors while keeping the existing order of elements in the vector, instead of having them automatically alphabetized. 4 | #' @keywords ordered factors 5 | #' @export 6 | #' @param myvector vector of character strings 7 | #' @examples 8 | #' mymonths <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") 9 | #' ordered_months_as_factors <- strings.to.ordered.factors(mymonths) 10 | 11 | 12 | strings_to_ordered_factors <- function(myvector){ 13 | myanswer <- factor(myvector, levels = unique(myvector), ordered=TRUE) 14 | return(myanswer) 15 | } 16 | -------------------------------------------------------------------------------- /man/getparty.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getpres.R 3 | \name{getparty} 4 | \alias{getparty} 5 | \title{Get US President's Polical Party by Date} 6 | \usage{ 7 | getparty(thedate) 8 | } 9 | \arguments{ 10 | \item{thedate}{Any date on or after 1945-04-12 as an R Date object.} 11 | } 12 | \description{ 13 | Get the US president's on a given date starting with Harry Truman (D) on 1945-04-12. 14 | } 15 | \details{ 16 | Input a date object on or after 1945-04-12 and get the name of the political party of the US president who was in office at that time. 17 | } 18 | \examples{ 19 | getparty(as.Date("2000-01-01")) 20 | } 21 | -------------------------------------------------------------------------------- /man/grapes-ni-grapes.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/ni.R 3 | \name{\%ni\%} 4 | \alias{\%ni\%} 5 | \title{"Not in" function} 6 | \usage{ 7 | ... \%ni\% NA 8 | } 9 | \arguments{ 10 | \item{myobject}{a vector} 11 | } 12 | \description{ 13 | Base R has the \%in\% function to create a logical vector whether one object is contained within another object. 14 | Why not \%ni\% to get a logical vector if one object is NOT contained within another? 15 | Idea from stackoverflow 16 | http://stackoverflow.com/questions/11302985/match-with-negation 17 | } 18 | \examples{ 19 | 5 \%ni\% c(2,4,6) 20 | # TRUE 21 | 22 | } 23 | \keyword{function} 24 | -------------------------------------------------------------------------------- /R/renamecol.R: -------------------------------------------------------------------------------- 1 | #' renamecol 2 | #' 3 | #' This function is a wrapper for the more cumbersome base R syntax 4 | #' colnames(mydf)[colnames(mydf) == 'oldcolname'] <- 'newcolname' 5 | #' or the function 6 | #' dplyr::rename(mydf,c('foo'='samples')) 7 | #' 8 | #' @param mydf dataframe with column to be renamed 9 | #' @param oldcolname character string existing column name 10 | #' @param newcolname character string desired new column name 11 | #' 12 | #' @return dataframe 13 | #' @export 14 | #' 15 | #' @examples 16 | #' new_mtcars <- renamecol(mtcars, "mpg", "MPG") 17 | #' 18 | renamecol <- function(mydf, oldcolname, newcolname){ 19 | colnames(mydf)[colnames(mydf) == oldcolname] <- newcolname 20 | return(mydf) 21 | } 22 | -------------------------------------------------------------------------------- /man/setindex_bygroup.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{setindex_bygroup} 4 | \alias{setindex_bygroup} 5 | \title{setindex_bygroup} 6 | \usage{ 7 | setindex_bygroup(mydf, mycolnum) 8 | } 9 | \arguments{ 10 | \item{mydf}{a data frame} 11 | 12 | \item{mycolnum}{Number of the id column for your data frame} 13 | } 14 | \description{ 15 | Create an auto-indexing column in a data frame grouped by an id column, with the index starting at 1 for each id column group. 16 | } 17 | \examples{ 18 | id <- c(1,1,2,2,2,3,4,4,5,5) 19 | cat <- c("A", "B", "A", "B", "C", "B", "C", "D", "A", "E") 20 | mydataframe <- data.frame(id, cat) 21 | mydataframe$step <- setindex_bygroup(mydataframe, 1) 22 | 23 | } 24 | -------------------------------------------------------------------------------- /man/removecolsAllNA.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/removecolsAllNA.R 3 | \name{removecolsAllNA} 4 | \alias{removecolsAllNA} 5 | \title{removecolsAllNA} 6 | \usage{ 7 | removecolsAllNA(mydf) 8 | } 9 | \arguments{ 10 | \item{mydf}{- data frame} 11 | } 12 | \value{ 13 | data frame 14 | } 15 | \description{ 16 | This function removes "empty" data frame columns where all the values are NA. It is a wrapper for this excellent StackOverflow answer http://stackoverflow.com/a/15968937/718150 17 | } 18 | \examples{ 19 | Cat <- c("CatA", "CatB", "CatC") 20 | Val1 <- c(4, 6, 5) 21 | Val2 <- c(NA, NA, NA) 22 | Val3 <- c(7, NA, 2) 23 | thedf <- data.frame(Cat, Val1, Val2, Val3) 24 | newdf <- removecolsAllNA(thedf) 25 | 26 | } 27 | -------------------------------------------------------------------------------- /R/removecolsAllNA.R: -------------------------------------------------------------------------------- 1 | #' removecolsAllNA 2 | #' 3 | #' This function removes "empty" data frame columns where all the values are NA. It is a wrapper for this excellent StackOverflow answer http://stackoverflow.com/a/15968937/718150 4 | #' 5 | #' @param mydf - data frame 6 | #' 7 | #' @return data frame 8 | #' @export 9 | #' 10 | #' @examples 11 | #' Cat <- c("CatA", "CatB", "CatC") 12 | #' Val1 <- c(4, 6, 5) 13 | #' Val2 <- c(NA, NA, NA) 14 | #' Val3 <- c(7, NA, 2) 15 | #' thedf <- data.frame(Cat, Val1, Val2, Val3) 16 | #' newdf <- removecolsAllNA(thedf) 17 | #' 18 | removecolsAllNA <- function(mydf){ 19 | # Wrapper for this excellent StackOverflow answer http://stackoverflow.com/a/15968937/718150 20 | newdf <- mydf[colSums(!is.na(mydf)) > 0] 21 | return(newdf) 22 | } 23 | -------------------------------------------------------------------------------- /R/edit_project_file.R: -------------------------------------------------------------------------------- 1 | 2 | 3 | #' Open file to edit RStudio project list 4 | #' 5 | #' Opens file for editing the RStudio dropdown project list so individual projects can be removed from the list. 6 | #' 7 | #' @param windrive For Windows only, drive where RStudio is installed. Defaults to C. 8 | #' 9 | #' @return action opens file 10 | #' @export 11 | #' 12 | #' @examples 13 | #' \dontrun{ 14 | #' edit_project_list() 15 | #' } 16 | edit_project_list <- function(windrive = "C"){ 17 | if(.Platform$OS.type == "windows"){ 18 | path <- paste0(windrive, ":/Users/", unname(Sys.info()['user']), "/AppData/Local/RStudio-Desktop/monitored/lists/project_mru") 19 | } else { 20 | path <- "~/.rstudio-desktop/monitored/lists/project_mru" 21 | } 22 | usethis::edit_file(path) 23 | } 24 | -------------------------------------------------------------------------------- /man/renamecol.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/renamecol.R 3 | \name{renamecol} 4 | \alias{renamecol} 5 | \title{renamecol} 6 | \usage{ 7 | renamecol(mydf, oldcolname, newcolname) 8 | } 9 | \arguments{ 10 | \item{mydf}{dataframe with column to be renamed} 11 | 12 | \item{oldcolname}{character string existing column name} 13 | 14 | \item{newcolname}{character string desired new column name} 15 | } 16 | \value{ 17 | dataframe 18 | } 19 | \description{ 20 | This function is a wrapper for the more cumbersome base R syntax 21 | colnames(mydf)[colnames(mydf) == 'oldcolname'] <- 'newcolname' 22 | or the function 23 | dplyr::rename(mydf,c('foo'='samples')) 24 | } 25 | \examples{ 26 | new_mtcars <- renamecol(mtcars, "mpg", "MPG") 27 | 28 | } 29 | -------------------------------------------------------------------------------- /man/strings_to_ordered_factors.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/factors.R 3 | \name{strings_to_ordered_factors} 4 | \alias{strings_to_ordered_factors} 5 | \title{strings_to_ordered_factors} 6 | \usage{ 7 | strings_to_ordered_factors(myvector) 8 | } 9 | \arguments{ 10 | \item{myvector}{vector of character strings} 11 | } 12 | \description{ 13 | Turn a vector of strings into a factors while keeping the existing order of elements in the vector, instead of having them automatically alphabetized. 14 | } 15 | \examples{ 16 | mymonths <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") 17 | ordered_months_as_factors <- strings.to.ordered.factors(mymonths) 18 | } 19 | \keyword{factors} 20 | \keyword{ordered} 21 | -------------------------------------------------------------------------------- /man/vector_to_single_string_w_linebreaks.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/strings.R 3 | \name{vector_to_single_string_w_linebreaks} 4 | \alias{vector_to_single_string_w_linebreaks} 5 | \title{vector_to_single_string_w_linebreaks} 6 | \usage{ 7 | vector_to_single_string_w_linebreaks(myvector, cr = 1) 8 | } 9 | \arguments{ 10 | \item{myvector}{A vector of character strings} 11 | 12 | \item{cr}{Number of line breaks after each element, defaults to 1} 13 | } 14 | \description{ 15 | This function takes a vector of character strings and turns it into a single string with line breaks after each item. 16 | } 17 | \examples{ 18 | vec <- c("Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun") 19 | vector_to_single_string(vec, 2) 20 | } 21 | \keyword{strings} 22 | -------------------------------------------------------------------------------- /man/rollingavg.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/rollingavg.R 3 | \name{rollingavg} 4 | \alias{rollingavg} 5 | \title{rollingavg} 6 | \usage{ 7 | rollingavg(myvec, n = 7) 8 | } 9 | \arguments{ 10 | \item{myvec}{Numerical vector from which you want to calculate a trailing average} 11 | 12 | \item{n}{Number of items to be used for each mean calculation, such as 7 for a 7-day trailing average} 13 | } 14 | \value{ 15 | The n-item trailing average of myvec 16 | } 17 | \description{ 18 | Generates an n-item trailing average vector from a numerical vector, after first removing any missing values. 19 | } 20 | \examples{ 21 | myvector <- c(100, 98, 97.5, 102, 96, 96.5, 97, 94, 92.3, 93, 95, 91, 89, 88, 88.5, 86) 22 | my7dayavg <- rollingavg(myvector) 23 | 24 | } 25 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export("%ni%") 4 | export(add_pct_cols_to_dataframe) 5 | export(add_row) 6 | export(add_row_from_list) 7 | export(copy_textfile_to_clipboard) 8 | export(edit_project_list) 9 | export(elec_find_winner) 10 | export(elec_pcts_by_row) 11 | export(getOS) 12 | export(getparty) 13 | export(getpres) 14 | export(maxn) 15 | export(mymode) 16 | export(na2zero) 17 | export(na2zero2) 18 | export(number_with_commas) 19 | export(read_textfile) 20 | export(removecolsAllNA) 21 | export(renamecol) 22 | export(rollingavg) 23 | export(setindex_bygroup) 24 | export(streaks) 25 | export(string2varname) 26 | export(strings_to_ordered_factors) 27 | export(table_sorted) 28 | export(toinitialcap) 29 | export(unlibrary) 30 | export(varname2string) 31 | export(vector_to_single_string_w_linebreaks) 32 | export(write_textfile) 33 | -------------------------------------------------------------------------------- /R/maxn.R: -------------------------------------------------------------------------------- 1 | 2 | #' maxn 3 | #' 4 | #' A function to find the top nth-highest value in a vector 5 | #' From kohske on StackOverflow 6 | #' http://stackoverflow.com/questions/10296866/finding-the-column-number-and-value-the-of-second-highest-value-in-a-row/10297025#10297025 7 | #' 8 | #' @param n vector of numbers 9 | #' 10 | #' @return top nth value 11 | #' @export 12 | #' 13 | #' @examples 14 | #' mydata <- c(6, 10, 2, 21, 13, 20, 4, 12) 15 | #' secondhighest <- mydata[maxn(2)(mydata)] 16 | #' 17 | #' # or define function for second highest: 18 | #' max2 <- maxn(2) 19 | #' secondhighest <- mydata[max2(mydata)] 20 | #' 21 | #' # To find second-highest number in each row in a dataframe: 22 | #' \dontrun{ 23 | #' apply(df, 1, function(x)x[maxn(2)(x)]) 24 | #' } 25 | #' 26 | #' 27 | maxn <- function(n){ 28 | function(x) order(x, decreasing = TRUE)[n] 29 | } 30 | 31 | -------------------------------------------------------------------------------- /man/add_row.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/add_row.R 3 | \name{add_row} 4 | \alias{add_row} 5 | \title{add_row Add one row of data to a data frame} 6 | \usage{ 7 | add_row(mydf, ...) 8 | } 9 | \arguments{ 10 | \item{mydf}{A data frame to which you'd like to add a row} 11 | 12 | \item{...}{Additional arguments in the format colname=value} 13 | } 14 | \description{ 15 | Easily add one row to a data frame when columns are not all of one class, when you have the format colname1 = value1, colname2 = value2, etc. Similar to SQL INSERT INTO. Maintains same class as original data frame. Any missing values will be changed to NA. 16 | } 17 | \details{ 18 | WARNING: THIS IS STILL A WORK IN PROGRESS!!! 19 | } 20 | \examples{ 21 | # Idea from Hadley Wickham 22 | add_row(mtcars, cyl = 4, disp = 7) 23 | 24 | } 25 | \keyword{dataframes} 26 | -------------------------------------------------------------------------------- /man/maxn.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/maxn.R 3 | \name{maxn} 4 | \alias{maxn} 5 | \title{maxn} 6 | \usage{ 7 | maxn(n) 8 | } 9 | \arguments{ 10 | \item{n}{vector of numbers} 11 | } 12 | \value{ 13 | top nth value 14 | } 15 | \description{ 16 | A function to find the top nth-highest value in a vector 17 | From kohske on StackOverflow 18 | http://stackoverflow.com/questions/10296866/finding-the-column-number-and-value-the-of-second-highest-value-in-a-row/10297025#10297025 19 | } 20 | \examples{ 21 | mydata <- c(6, 10, 2, 21, 13, 20, 4, 12) 22 | secondhighest <- mydata[maxn(2)(mydata)] 23 | 24 | # or define function for second highest: 25 | max2 <- maxn(2) 26 | secondhighest <- mydata[max2(mydata)] 27 | 28 | # To find second-highest number in each row in a dataframe: 29 | \dontrun{ 30 | apply(df, 1, function(x)x[maxn(2)(x)]) 31 | } 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /R/rollingavg.R: -------------------------------------------------------------------------------- 1 | #' rollingavg 2 | #' 3 | #' Generates an n-item trailing average vector from a numerical vector, after first removing any missing values. 4 | #' 5 | #' @param myvec Numerical vector from which you want to calculate a trailing average 6 | #' @param n Number of items to be used for each mean calculation, such as 7 for a 7-day trailing average 7 | #' @return The n-item trailing average of myvec 8 | #' @export 9 | #' 10 | #' @examples 11 | #' myvector <- c(100, 98, 97.5, 102, 96, 96.5, 97, 94, 92.3, 93, 95, 91, 89, 88, 88.5, 86) 12 | #' my7dayavg <- rollingavg(myvector) 13 | #' 14 | rollingavg <- function(myvec, n=7){ 15 | numvals <- length(myvec) 16 | myvec <- myvec[!is.na(myvec)] 17 | nminus1 <- n-1 18 | movavgitem <- vector(mode="numeric", length=numvals) 19 | for(i in 1:numvals){ 20 | if(i >= n){ 21 | movavgitem[i] <- sum(myvec[i:(i-nminus1)]) / n 22 | } else { 23 | movavgitem[i] <- NA 24 | } 25 | } 26 | return(movavgitem) 27 | } 28 | -------------------------------------------------------------------------------- /man/add_row_from_list.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/add_row_from_list.R 3 | \name{add_row_from_list} 4 | \alias{add_row_from_list} 5 | \title{add_row_from_list Add one row of data to a data frame from a list} 6 | \usage{ 7 | add_row_from_list(mydf, mylist) 8 | } 9 | \arguments{ 10 | \item{mydf}{A data frame to which you'd like to add a row} 11 | 12 | \item{mylist}{A list holding a single row of data, 13 | in the exact order of columns in the original data frame.} 14 | } 15 | \description{ 16 | Easily add one row to a data frame when columns are not all of one class. Data should be in a list format, one row only, in same order as columns in the original data frame. Any missing values must be explicitly included as NAs. Similar to SQL INSERT INTO. Maintains same class as original data frame. 17 | } 18 | \details{ 19 | WARNING: THIS IS STILL A WORK IN PROGRESS!!! 20 | } 21 | \examples{ 22 | # Idea from Jennifer Bryan 23 | add_row_from_list(iris, list(5.1, 3.5, 1.4, 0.2, "setosa")) 24 | 25 | 26 | } 27 | \keyword{dataframes} 28 | -------------------------------------------------------------------------------- /man/streaks.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/streaks.R 3 | \name{streaks} 4 | \alias{streaks} 5 | \title{streaks} 6 | \usage{ 7 | streaks(myvector, streakitem = "W", nonstreakitem = "L") 8 | } 9 | \arguments{ 10 | \item{myvector}{a vector of characters or numbers such as 0 and 1.} 11 | 12 | \item{streakitem}{a character or number that stands for the item you're seeking a streak for, such as "W" or 1.} 13 | 14 | \item{nonstreakitem}{a character or number that stands for the item that usually interrupts the streak, such as "L" when seeking "W" streaks. There can be other streak-interrupting items not identified, such as "T" for ties.} 15 | } 16 | \description{ 17 | Function to find streaks in a vector, typically winning or losing streaks. 18 | Slight modification of function by Jim Albert at https://baseballwithr.wordpress.com/2014/07/07/team-streaks-part-i-2/ 19 | } 20 | \examples{ 21 | seasonrecord <- c("Win", "Win", "Win", "Loss", "Loss", "Win", "Tie", "Win", "Win", "Win", "Win", "Win", "Win", "Win", "Loss", "Win") 22 | streaks(seasonrecord, "Win", "Loss") 23 | } 24 | \keyword{baseball} 25 | -------------------------------------------------------------------------------- /R/streaks.R: -------------------------------------------------------------------------------- 1 | #' streaks 2 | #' 3 | #' Function to find streaks in a vector, typically winning or losing streaks. 4 | #' Slight modification of function by Jim Albert at https://baseballwithr.wordpress.com/2014/07/07/team-streaks-part-i-2/ 5 | #' 6 | #' @keywords baseball 7 | #' @export 8 | #' @param myvector a vector of characters or numbers such as 0 and 1. 9 | #' @param streakitem a character or number that stands for the item you're seeking a streak for, such as "W" or 1. 10 | #' @param nonstreakitem a character or number that stands for the item that usually interrupts the streak, such as "L" when seeking "W" streaks. There can be other streak-interrupting items not identified, such as "T" for ties. 11 | #' @examples 12 | #' seasonrecord <- c("Win", "Win", "Win", "Loss", "Loss", "Win", "Tie", "Win", "Win", "Win", "Win", "Win", "Win", "Win", "Loss", "Win") 13 | #' streaks(seasonrecord, "Win", "Loss") 14 | 15 | streaks <- function(myvector, streakitem="W", nonstreakitem="L"){ 16 | n <- length(myvector) 17 | where <- c(nonstreakitem, myvector, nonstreakitem) != streakitem 18 | location.zeros <- (0 : (n + 1))[where] 19 | streak.lengths <- diff(location.zeros) - 1 20 | streak.lengths <- streak.lengths[streak.lengths > 0] 21 | return(streak.lengths) 22 | } 23 | -------------------------------------------------------------------------------- /man/elec_pcts_by_row.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/elect_pcts_by_row.R 3 | \name{elec_pcts_by_row} 4 | \alias{elec_pcts_by_row} 5 | \title{elec_pcts_by_row} 6 | \usage{ 7 | elec_pcts_by_row(df, mycols, totalcol = "Total") 8 | } 9 | \arguments{ 10 | \item{df}{data frame that contains at least one numeric column.} 11 | 12 | \item{mycols}{character strings - names of columns with numerical data for which you'd like to calculate percentages across rows.} 13 | 14 | \item{totalcol}{character string - name of column that has vote (or other) totals.} 15 | } 16 | \value{ 17 | data frame 18 | } 19 | \description{ 20 | This function lets you select columns in a data frame with raw numbers and will add columns with percent data by row. This is particular useful for election results where each row contains data by precinct, city, etc. and each column is a different candidate, ballot question yes/no, or similar construct. 21 | } 22 | \details{ 23 | This is a modification of the pct function from the caroline package by David Schruth. 24 | } 25 | \examples{ 26 | City <- c("Cityville", "Townville", "Placeville") 27 | Yes <- c(250, 100, 150) 28 | No <- c(200, 200, 300) 29 | mydf <- data.frame(City, Yes, No) 30 | mydf$Total <- mydf$Yes + mydf$No 31 | 32 | } 33 | -------------------------------------------------------------------------------- /man/add_pct_cols_to_dataframe.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/add_pct_cols_to_dataframe.R 3 | \name{add_pct_cols_to_dataframe} 4 | \alias{add_pct_cols_to_dataframe} 5 | \title{add_pct_cols_to_dataframe} 6 | \usage{ 7 | add_pct_cols_to_dataframe(df, mycols, totalcol = "Total") 8 | } 9 | \arguments{ 10 | \item{df}{data frame that contains at least one numeric column.} 11 | 12 | \item{mycols}{character strings - names of columns with numerical data for which you'd like to calculate percentages across rows.} 13 | 14 | \item{totalcol}{character string - name of column that has vote (or other) totals.} 15 | } 16 | \value{ 17 | data frame 18 | } 19 | \description{ 20 | This function lets you select columns in a data frame with raw numbers and will add columns with percent data by row. This is particular useful for election results where each row contains data by precinct, city, etc. and each column is a different candidate, ballot question yes/no, or similar construct. 21 | } 22 | \details{ 23 | This is a modification of the pct function from the caroline package by David Schruth. 24 | } 25 | \examples{ 26 | City <- c("Cityville", "Townville", "Placeville") 27 | Yes <- c(250, 100, 150) 28 | No <- c(200, 200, 300) 29 | mydf <- data.frame(City, Yes, No) 30 | mydf$Total <- mydf$Yes + mydf$No 31 | 32 | } 33 | -------------------------------------------------------------------------------- /R/elect_pcts_by_row.R: -------------------------------------------------------------------------------- 1 | #' elec_pcts_by_row 2 | #' 3 | #' This function lets you select columns in a data frame with raw numbers and will add columns with percent data by row. This is particular useful for election results where each row contains data by precinct, city, etc. and each column is a different candidate, ballot question yes/no, or similar construct. 4 | #' 5 | #' This is a modification of the pct function from the caroline package by David Schruth. 6 | #' 7 | #' @param df data frame that contains at least one numeric column. 8 | #' @param mycols character strings - names of columns with numerical data for which you'd like to calculate percentages across rows. 9 | #' @param totalcol character string - name of column that has vote (or other) totals. 10 | #' 11 | #' @return data frame 12 | #' @export 13 | #' 14 | #' @examples 15 | #' City <- c("Cityville", "Townville", "Placeville") 16 | #' Yes <- c(250, 100, 150) 17 | #' No <- c(200, 200, 300) 18 | #' mydf <- data.frame(City, Yes, No) 19 | #' mydf$Total <- mydf$Yes + mydf$No 20 | # mydf <- elec_pcts_by_row(mydf, c("Yes", "No")) 21 | #' 22 | elec_pcts_by_row <- function (df, mycols, totalcol = "Total"){ 23 | #modification of pct from caroline package to do percents by rows 24 | for (i in mycols){ 25 | df[paste(i, "pct", sep = ".")] <- round(df[i] / df[totalcol], 3) * 100 26 | } 27 | return(df) 28 | } 29 | -------------------------------------------------------------------------------- /R/add_row.R: -------------------------------------------------------------------------------- 1 | #' add_row Add one row of data to a data frame 2 | #' 3 | #' Easily add one row to a data frame when columns are not all of one class, when you have the format colname1 = value1, colname2 = value2, etc. Similar to SQL INSERT INTO. Maintains same class as original data frame. Any missing values will be changed to NA. 4 | #' 5 | #' WARNING: THIS IS STILL A WORK IN PROGRESS!!! 6 | #' 7 | #' @param mydf A data frame to which you'd like to add a row 8 | #' @param ... Additional arguments in the format colname=value 9 | #' @keywords dataframes 10 | #' @export 11 | #' @examples 12 | #' # Idea from Hadley Wickham 13 | #' add_row(mtcars, cyl = 4, disp = 7) 14 | #' 15 | 16 | add_row <- function(mydf, ...){ 17 | colClasses <- sapply(mydf, class) 18 | newrownum <- nrow(mydf) + 1 19 | newrowdata <- list(...) 20 | allCols <- names(mydf) 21 | definedCols <- names(newrowdata) 22 | # check to make sure column names defined properly 23 | 24 | typocheck <- definedCols %in% allCols 25 | if(!(all(typocheck))){ 26 | cat("You have a typo in one of your column names") 27 | break 28 | } 29 | 30 | # set proper classes 31 | for(eachnewcol in definedCols){ 32 | class(newrowdata[[eachnewcol]]) <- class(mydf[[eachnewcol]]) 33 | } 34 | 35 | # add data from arguments 2 and beyond to the data frame 36 | for(eachcol in allCols ){ 37 | mydf[newrownum, eachcol] <- ifelse(eachcol %in% definedCols, newrowdata[eachcol], NA) 38 | } 39 | return(mydf) 40 | } 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /R/add_row_from_list.R: -------------------------------------------------------------------------------- 1 | #' add_row_from_list Add one row of data to a data frame from a list 2 | #' 3 | #' Easily add one row to a data frame when columns are not all of one class. Data should be in a list format, one row only, in same order as columns in the original data frame. Any missing values must be explicitly included as NAs. Similar to SQL INSERT INTO. Maintains same class as original data frame. 4 | #' 5 | #' WARNING: THIS IS STILL A WORK IN PROGRESS!!! 6 | #' 7 | #' @param mydf A data frame to which you'd like to add a row 8 | #' @param mylist A list holding a single row of data, 9 | #' in the exact order of columns in the original data frame. 10 | #' @keywords dataframes 11 | #' @export 12 | #' @examples 13 | #' # Idea from Jennifer Bryan 14 | #' add_row_from_list(iris, list(5.1, 3.5, 1.4, 0.2, "setosa")) 15 | #' 16 | #' 17 | 18 | add_row_from_list <- function(mydf, mylist){ 19 | colClasses <- sapply(mydf, class) 20 | 21 | # check to make sure length of list is same as number of columns in data frame 22 | if(ncol(mydf) != length(mylist)){ 23 | cat("Your list must be the same length as the number of columns in your data frame") 24 | break 25 | } 26 | 27 | # set proper classes 28 | for(i in 1:ncol(mydf)){ 29 | if (is.factor(mydf[[1,i]])){ 30 | myfactors <- mydf[[i]] 31 | myfactors[length(myfactors) + 1] <- mylist[[i]] 32 | mylist[[i]] <- myfactors[length(myfactors)] 33 | } else { 34 | 35 | class(mylist[[i]]) <- class(mydf[1,i]) 36 | } 37 | 38 | # add mylist to data frame 39 | newdf <- rbind(mydf, mylist) 40 | return(newdf) 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /R/add_pct_cols_to_dataframe.R: -------------------------------------------------------------------------------- 1 | #' add_pct_cols_to_dataframe 2 | #' 3 | #' This function lets you select columns in a data frame with raw numbers and will add columns with percent data by row. This is particular useful for election results where each row contains data by precinct, city, etc. and each column is a different candidate, ballot question yes/no, or similar construct. 4 | #' 5 | #' This is a modification of the pct function from the caroline package by David Schruth. 6 | #' 7 | #' @param df data frame that contains at least one numeric column. 8 | #' @param mycols character strings - names of columns with numerical data for which you'd like to calculate percentages across rows. 9 | #' @param totalcol character string - name of column that has vote (or other) totals. 10 | #' 11 | #' @return data frame 12 | #' @export 13 | #' 14 | #' @examples 15 | #' City <- c("Cityville", "Townville", "Placeville") 16 | #' Yes <- c(250, 100, 150) 17 | #' No <- c(200, 200, 300) 18 | #' mydf <- data.frame(City, Yes, No) 19 | #' mydf$Total <- mydf$Yes + mydf$No 20 | # mydf <- add_pct_cols_to_dataframe(mydf, c("Yes", "No")) 21 | #' 22 | add_pct_cols_to_dataframe <- function (df, mycols, totalcol = "Total"){ 23 | #modification of pct from caroline package to do percents by rows 24 | for (i in mycols){ 25 | df[paste(i, "pct", sep = ".")] <- round(df[i] / df[totalcol], 3) 26 | } 27 | return(df) 28 | } 29 | 30 | City <- c("Cityville", "Townville", "Placeville") 31 | Yes <- c(250, 100, 150) 32 | No <- c(200, 200, 300) 33 | mydf <- data.frame(City, Yes, No) 34 | mydf$Total <- mydf$Yes + mydf$No 35 | mydf <- add_pct_cols_to_dataframe(mydf, c("Yes", "No")) 36 | -------------------------------------------------------------------------------- /man/elec_find_winner.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/elec_find_winner.R 3 | \name{elec_find_winner} 4 | \alias{elec_find_winner} 5 | \title{find_winner} 6 | \usage{ 7 | elec_find_winner(filename, datacolstart, datacolstop, exportcsv = TRUE) 8 | } 9 | \arguments{ 10 | \item{filename}{string name of file, either spreadsheet or csv, including extension and file path if not in your working directory. If name does not include ".csv", ".tsv", ".xlsx", ".xls", or ".ods", function assumes that you want to use the name of a data frame that already exists in your working environment.} 11 | 12 | \item{datacolstart}{integer number of the column where the results data starts. If data starts in column B of an Excel spreadsheet, for example, datacolstart should be 2.} 13 | 14 | \item{datacolstop}{integer number of the column where the results data ends} 15 | 16 | \item{exportcsv}{Boolean If you want results saved to a csv file (name is same as filename_winners.csv)} 17 | } 18 | \value{ 19 | dataframe 20 | } 21 | \description{ 22 | This function finds the top vote-getter in a csv or Excel election results file - it looks for the largest number in each row and creates a new column with the name of the winner(s) (more specifically, the column name with the maximum value for each row). Accounts for ties. Requires rio package. 23 | } 24 | \details{ 25 | Results file must have candidate results in adjoining columns, in a format with each candidate having their own column of results. findwinner function arguments: filename (string), datacolstart (number of data column where results data starts; 2 for column B in Excel, for example), datacolstop (number of the last dat… 26 | } 27 | \examples{ 28 | \dontrun{ 29 | mydata <- find_winner("results.xlsx", 2, 4) 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /R/elec_find_winner.R: -------------------------------------------------------------------------------- 1 | #' find_winner 2 | #' 3 | #' This function finds the top vote-getter in a csv or Excel election results file - it looks for the largest number in each row and creates a new column with the name of the winner(s) (more specifically, the column name with the maximum value for each row). Accounts for ties. Requires rio package. 4 | #' 5 | #' Results file must have candidate results in adjoining columns, in a format with each candidate having their own column of results. findwinner function arguments: filename (string), datacolstart (number of data column where results data starts; 2 for column B in Excel, for example), datacolstop (number of the last dat… 6 | #' 7 | #' @param filename string name of file, either spreadsheet or csv, including extension and file path if not in your working directory. If name does not include ".csv", ".tsv", ".xlsx", ".xls", or ".ods", function assumes that you want to use the name of a data frame that already exists in your working environment. 8 | #' @param datacolstart integer number of the column where the results data starts. If data starts in column B of an Excel spreadsheet, for example, datacolstart should be 2. 9 | #' @param datacolstop integer number of the column where the results data ends 10 | #' @param exportcsv Boolean If you want results saved to a csv file (name is same as filename_winners.csv) 11 | #' 12 | #' @return dataframe 13 | #' @export 14 | #' 15 | #' @examples 16 | #' \dontrun{ 17 | #' mydata <- find_winner("results.xlsx", 2, 4) 18 | #' } 19 | #' 20 | elec_find_winner <- function (filename, datacolstart, datacolstop, exportcsv = TRUE) 21 | { 22 | matches <- "\\.tsv|\\.xlsx|\\.xls|\\.ods" 23 | if(grepl("\\.csv$", filename)){ 24 | data <- readr::read_csv(filename) 25 | } else if(grepl(matches, filename)){ 26 | data <- rio::import(filename) 27 | } else { 28 | data <- eval(parse(text = filename)) 29 | } 30 | 31 | # Fix problems if tibble 32 | data <- as.data.frame(data) 33 | 34 | for(i in 1:nrow(data)){ 35 | ranks <- rank(data[i,datacolstart:datacolstop]) 36 | maxrank <- as.numeric(max(ranks)) 37 | winners <- names(ranks[ranks==maxrank]) 38 | data$Winner[i] <- paste(winners, collapse = ", ") 39 | } 40 | 41 | if (exportcsv) { 42 | filename_root <- strsplit(filename, "\\.")[[1]][1] 43 | filename_with_winner <- paste0(filename_root, "_winners.csv") 44 | rio::export(data, filename_with_winner) 45 | } 46 | return(data) 47 | } 48 | -------------------------------------------------------------------------------- /R/strings.R: -------------------------------------------------------------------------------- 1 | #' toinitialcap 2 | #' 3 | #' Base R has toupper and tolower - why not toinitialcap? 4 | #' This renames the example .simpleCap function in the toupper help file. 5 | #' @param mystring (any string) 6 | #' @keywords strings 7 | #' @export 8 | #' @examples 9 | #' toinitialcap("this is a headline") 10 | 11 | toinitialcap <- function(mystring){ 12 | s <- strsplit(mystring, " ")[[1]] 13 | paste(toupper(substring(s, 1, 1)), substring(s, 2), 14 | sep = "", collapse = " ") 15 | } 16 | 17 | #' vector_to_single_string_w_linebreaks 18 | #' 19 | #' This function takes a vector of character strings and turns it into a single string with line breaks after each item. 20 | #' @param myvector A vector of character strings 21 | #' @param cr Number of line breaks after each element, defaults to 1 22 | #' @keywords strings 23 | #' @export 24 | #' @examples 25 | #' vec <- c("Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun") 26 | #' vector_to_single_string(vec, 2) 27 | 28 | 29 | vector_to_single_string_w_linebreaks <- function(myvector, cr=1){ 30 | carriagereturns <- rep("\n", cr) 31 | carriagereturns <- paste(carriagereturns, collapse="") 32 | mystring <- paste(myvector, collapse=carriagereturns) 33 | return(mystring) 34 | } 35 | 36 | #' copy_textfile_to_clipboard 37 | #' 38 | #' This function takes the path to a textfile as a character string and reads it into the Windows or Mac clipboards only. 39 | #' @param mytextfile Path to a text file as a character string 40 | #' @keywords clipboard 41 | #' @export 42 | #' @examples 43 | #' myfile <- "data/textfile.txt" 44 | #' copy_textfile_to_clipboard(myfile) 45 | 46 | copy_textfile_to_clipboard <- function(mytextfile) { 47 | if(Sys.info()["sysname"]=="Windows"){ 48 | mystring <- readChar(mytextfile, file.info(mytextfile)$size) 49 | cat(mystring,file="clipboard",sep=' ') 50 | } else { 51 | myclipboard <- pipe('pbcopy','w') 52 | cat(mytextfile,file=myclipboard,sep=' ') 53 | close(myclipboard) 54 | } 55 | } 56 | 57 | 58 | 59 | 60 | #' string2varname 61 | #' 62 | #' This function takes a string and turns it into a variable name. 63 | #' Code from John Ramey at http://johnramey.net/blog/2010/12/28/converting-a-string-to-a-variable-name-on-the-fly-and-vice-versa-in-r/ 64 | #' 65 | #' @param x string 66 | #' 67 | #' @return value of variable with name equal to the string 68 | #' @export 69 | #' 70 | #' @examples 71 | #' x <- 42 72 | #' eval(parse(text = "x")) 73 | #' # [1] 42 74 | #' 75 | string2varname <- function(x){ 76 | eval(parse(text = "x")) 77 | } 78 | 79 | 80 | 81 | #' varname2string 82 | #' 83 | #' This function takes a variable name and turns it into a string. 84 | #' Code from John Ramey at http://johnramey.net/blog/2010/12/28/converting-a-string-to-a-variable-name-on-the-fly-and-vice-versa-in-r/ 85 | #' 86 | #' @param x variable name 87 | #' 88 | #' @return string 89 | #' @export 90 | #' 91 | #' @examples 92 | #' x <- 42 93 | #' varname2string(x) 94 | #' # [1] "x" 95 | #' 96 | varname2string <- function(x){ 97 | deparse(substitute(x)) 98 | } 99 | -------------------------------------------------------------------------------- /R/getpres.R: -------------------------------------------------------------------------------- 1 | #' Get US President by Date 2 | #' 3 | #' Get the name of US president on a given date starting with Harry Truman. 4 | #' 5 | #' Input a date object on or after 1945-04-12 and get the name of the US president who was in office at that time. 6 | #' @param thedate Any date on or after 1945-04-12 as an R Date object. 7 | #' @export 8 | #' @examples 9 | #' getpres(as.Date("2000-01-01")) 10 | 11 | getpres <- function(thedate){ 12 | #help on StackOverflow to use cut() instead of nested if-else statements 13 | # http://stackoverflow.com/questions/29053623/use-r-switch-for-less-than-or-greater-than 14 | thepres <- cut(thedate, 15 | c(as.Date("1945-04-12"), 16 | as.Date("1953-01-21"), 17 | as.Date("1961-01-20"), 18 | as.Date("1963-11-22"), 19 | as.Date("1969-01-20"), 20 | as.Date("1974-01-20"), 21 | as.Date("1977-01-20"), 22 | as.Date("1981-01-20"), 23 | as.Date("1989-01-20"), 24 | as.Date("1993-01-20"), 25 | as.Date("2001-01-20"), 26 | as.Date("2009-01-20"), 27 | as.Date("2017-01-20")), 28 | labels=c("Truman","Eisenhower", "Kennedy", "Johnson", 29 | "Nixon", "Ford", "Carter", "Reagan", "George HW Bush", 30 | "Clinton", "George W Bush", "Obama", "Trump"), right=F) 31 | 32 | return(as.character(thepres)) 33 | 34 | } 35 | 36 | 37 | 38 | #' Get US President's Polical Party by Date 39 | #' 40 | #' Get the US president's on a given date starting with Harry Truman (D) on 1945-04-12. 41 | #' 42 | #' Input a date object on or after 1945-04-12 and get the name of the political party of the US president who was in office at that time. 43 | #' @param thedate Any date on or after 1945-04-12 as an R Date object. 44 | #' @export 45 | #' @examples 46 | #' getparty(as.Date("2000-01-01")) 47 | 48 | 49 | getparty <- function(thedate){ 50 | #help on StackOverflow to use cut() instead of nested if-else statements 51 | # http://stackoverflow.com/questions/29053623/use-r-switch-for-less-than-or-greater-than 52 | theparty <- cut(thedate, 53 | c(as.Date("1945-04-12"), 54 | as.Date("1953-01-21"), 55 | as.Date("1961-01-20"), 56 | as.Date("1963-11-22"), 57 | as.Date("1969-01-20"), 58 | as.Date("1974-01-20"), 59 | as.Date("1977-01-20"), 60 | as.Date("1981-01-20"), 61 | as.Date("1989-01-20"), 62 | as.Date("1993-01-20"), 63 | as.Date("2001-01-01"), 64 | as.Date("2009-01-01"), 65 | as.Date("2016-01-20")), 66 | labels=c("Democrat","Republican", "Democrat", "Democrat", 67 | "Republican", "Republican", "Democrat", "Republican", "Republican", 68 | "Democrat", "Republican", "Democrat"), right=F) 69 | 70 | return(as.character(theparty)) 71 | 72 | } 73 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /R/misc.R: -------------------------------------------------------------------------------- 1 | #' unlibrary 2 | #' 3 | #' Opposite of library - wrapper to detach a package 4 | #' 5 | #' @keywords environment 6 | #' @export 7 | #' @param pkgname name of a package as a character string in quotation marks 8 | #' @examples 9 | #' unlibrary(devtools) 10 | #' 11 | unlibrary <- function(pkgname){ 12 | unloadNamespace(pkgname) 13 | } 14 | 15 | 16 | #' getOS 17 | #' 18 | #' Wrapper to see what operating system is running 19 | #' 20 | #' @keywords environment 21 | #' @export 22 | #' @examples 23 | #' getOS() 24 | #' 25 | getOS <- function(){ 26 | Sys.info()['sysname'] 27 | } 28 | 29 | 30 | #' table_sorted 31 | #' 32 | #' Get a frequency table from a vector of categorical variables sorted by frequency in descending order 33 | #' 34 | #' @export 35 | #' @examples 36 | #' myvec <- c("white", "blue", "purple", "white", "blue", "blue", "blue", "purple", "yellow", "white") 37 | #' table_sorted(myvec) 38 | 39 | 40 | table_sorted <- function(myvector){ 41 | sort(table(myvector), decreasing = TRUE) 42 | } 43 | 44 | #' read_textfile 45 | #' 46 | #' Read a text file into a variable as a single character string 47 | #' 48 | #' @export 49 | #' @param filename name of a file as a character string in quotation marks 50 | #' @examples 51 | #' mystring <- read_textfile("myfile.txt") 52 | #' 53 | read_textfile <- function(filename){ 54 | mystring <- readChar(filename, file.info(filename)$size) 55 | return(mystring) 56 | } 57 | 58 | 59 | 60 | 61 | #' write_textfile 62 | #' 63 | #' Write a variable with one or more character strings to a text file taken from this stackoverflow answer http://stackoverflow.com/a/2470277/718150 64 | #' 65 | #' @param myvar Variable that holds character string data 66 | #' @param myfilename string Name of the file 67 | #' 68 | #' @export 69 | #' 70 | #' @examples 71 | #' \dontrun{ 72 | #' write_textfile(mydata, "myfile.txt") 73 | #'} 74 | 75 | write_textfile <- function(myvar, myfilename){ 76 | fileConn<-file(myfilename) 77 | writeLines(myvar, fileConn) 78 | close(fileConn) 79 | 80 | } 81 | 82 | 83 | 84 | #' setindex_bygroup 85 | #' 86 | #' Create an auto-indexing column in a data frame grouped by an id column, with the index starting at 1 for each id column group. 87 | #' 88 | #' @export 89 | #' @param mydf a data frame 90 | #' @param mycolnum Number of the id column for your data frame 91 | #' @examples 92 | #' id <- c(1,1,2,2,2,3,4,4,5,5) 93 | #' cat <- c("A", "B", "A", "B", "C", "B", "C", "D", "A", "E") 94 | #' mydataframe <- data.frame(id, cat) 95 | #' mydataframe$step <- setindex_bygroup(mydataframe, 1) 96 | #' 97 | 98 | setindex_bygroup <- function(mydf, mycolnum){ 99 | ave(1:nrow(mydf), factor(mydf[,mycolnum]), FUN=function(x) 1:length(x) ) 100 | } 101 | 102 | #' na2zero 103 | #' 104 | #' Turn all the NA values in a data frame to zero. 105 | #' 106 | #' @export 107 | #' @param mydf a data frame 108 | #' @examples 109 | #' newdf <- na2zero(mydf) 110 | #' 111 | na2zero <- function(mydf){ 112 | mydf[is.na(mydf)] <- 0 113 | return(mydf) 114 | } 115 | 116 | 117 | #' na2zero2 118 | #' 119 | #' Turn all the NA values in a data frame to zero but only in columns that are numeric or integers. Uses for loops, so may be slow for large data frames. 120 | #' 121 | #' @export 122 | #' @param mydf a data frame 123 | #' @examples 124 | #' 125 | #' x1 <- c(5,7,NA,9,10) 126 | #' x2 <- c(2.4, 7, 6.4, NA,5.2) 127 | #' x3 <- c(NA, "A", "B", "C", "D") 128 | #' x <- data.frame(x1,x2,x3) 129 | #' newdf <- na2zero2(x) 130 | #' 131 | 132 | na2zero2 <- function(mydf){ 133 | for(i in 1:nrow(mydf)){ 134 | for(j in 1:ncol(mydf)){ 135 | if(is.na(mydf[i,j]) && (is.numeric(mydf[,j]) || is.integer(mydf[,j]))){ 136 | mydf[i,j] <- 0 137 | } 138 | } 139 | } 140 | return(mydf) 141 | } 142 | 143 | 144 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | This package is a collection of simple R functions that I’ve either 3 | written or discovered over the years that I’ve found useful and like to 4 | re-use. In some cases, these functions are just thin wrappers around 5 | other functions but the syntax is easier for me to remember. 6 | 7 | This is a work in progress. 8 | 9 | To install, you need to have the devtools package on your system (if you 10 | don’t have it, install that with install.packages(“devtools”) ) and then 11 | run 12 | 13 | ``` r 14 | devtools::install_github("smach/rmiscutils") 15 | ``` 16 | 17 | Some of the tasks that functions in this package accomplish: 18 | 19 | Add a row to a dataframe with the format 20 | 21 | ``` r 22 | add_row(mydf, col1 = 4, col2 = 7, col3="A") 23 | ``` 24 | 25 | `add_row` 26 | 27 | Add a row to a dataframe with the format 28 | 29 | ``` r 30 | add_row_from_list(iris, list(5.1, 3.5, 1.4, 0.2, "setosa")) 31 | ``` 32 | 33 | `add_row_from_list` 34 | 35 | Calculate percentages from selected data frame columns by row, and add 36 | new columns with that data. Designed for election results. 37 | `add_pct_cols_to_dataframe` 38 | 39 | Calculate the statistical mode of a vector (which base R oddly does not 40 | do). `mymode` 41 | 42 | Capitalizes the first letter of each word in a string. (Note: base R 43 | 3.2.0 subsequently included the `tools::toTitleCase(`) function, but 44 | toinitialcap has the advantage of naming consistency with base R’s 45 | `tolower` and `toupper`). `toinitialcap` – to go along with base R’s 46 | tolower() and toupper(), 47 | 48 | Convert all NA values in a data frame to zeroes. `na2zero` 49 | 50 | Convert only NA values to zeroes in data frame columns that are numeric 51 | or integers. Uses for loops, so may be slow for large data frames. 52 | `na2zero2` 53 | 54 | Convert character strings containing numbers with commas into numbers. 55 | `numbers_with_commas` 56 | 57 | Convert a vector of character strings into an ordered factor, keeping 58 | the original order. Helpful if x-axis order is important when 59 | visualizing data. (Created before the forcats package). 60 | `strings_to_ordered_factors` 61 | 62 | Create a frequency table sorted by descending frequency. (Would probably 63 | use a version of `janitor::tabyl` today) `table_sorted` 64 | 65 | Find winning candidates in a spreadsheet or data frame of election 66 | results. `elec_find_winner` 67 | 68 | Find winning (or other) streaks in a vector of data. This is a slightly 69 | modified function from [Exploring Baseball Data with 70 | R](https://baseballwithr.wordpress.com/2014/07/07/team-streaks-part-i-2/). 71 | `streaks` 72 | 73 | Open the file that allows you to edit the RStudio dropdown list of 74 | projects. `edit_project_list()` 75 | 76 | Read a text file into an R variable as a single character string. 77 | `read_textfile` 78 | 79 | Rename a single data frame column using format 80 | `renamecol(mydf, oldcolname, newcolname)` `renamecol` 81 | 82 | Remove columns from a data frame where *all* values are NA. Useful when 83 | importing spreadsheets or CSV files where there are some empty columns. 84 | `removecolsAllNA` 85 | 86 | Unload a package from current working session. Because it can be 87 | difficult to remember that 88 | `detach("package:mypackagename", unload=TRUE)` or 89 | `unloadNamespace("mypackagename")` are the opposites of 90 | `library("mypackagename")`. `unlibrary` 91 | 92 | Write an object containing character string data to a text file. 93 | `write_textfile` 94 | 95 | From a character string, return the value of an object with that name 96 | (there’s also string2varname, which does the reverse) `varname2string` 97 | 98 | To see a complete list of available function and links to their help 99 | files, run 100 | 101 | ``` r 102 | help(package = "rmiscutils") 103 | ``` 104 | 105 | Some of the package’s functions by function name: 106 | ------------------------------------------------- 107 | 108 | *add\_pct\_cols\_to\_dataframe* – designed for election results, will 109 | calculate percentages from selected columns by row and add new columns 110 | with that data. 111 | 112 | *add\_row* – add a row to a dataframe with the format 113 | 114 | ``` r 115 | add_row(mydf, col1 = 4, col2 = 7, col3="A") 116 | ``` 117 | 118 | Thanks to Hadely Wickham for that function idea. 119 | 120 | *add\_row\_from\_list* – add a row to a dataframe with the format 121 | 122 | ``` r 123 | add_row_from_list(iris, list(5.1, 3.5, 1.4, 0.2, "setosa")) 124 | ``` 125 | 126 | Thanks to Jennifer Bryan for that function idea. 127 | 128 | *edit\_project\_list* – opens the file that controls RStudio’s dropdown 129 | project list. 130 | 131 | *mymode* – calculates the statistical mode of a vector, which base R 132 | oddly does not do. 133 | 134 | *na2zero* – turn all NA values in a data frame to zeroes. 135 | 136 | *na2zero2* – turns only NA values to zeroes in data frame columns that 137 | are numeric or integers. Uses for loops, so may be slow for large data 138 | frames. 139 | 140 | *number\_with\_commas* – easily turn character strings containing 141 | numbers with commas into numbers. 142 | 143 | *read\_textfile* – read a text file into an R variable as a single 144 | character string. 145 | 146 | *renamecol* – rename a single column in a dataframe using format 147 | renamecol(mydf, oldcolname, newcolname) 148 | 149 | *removecolsAllNA* – remove columns from a data frame where *all* values 150 | are NA. Useful when importing spreadsheets or CSV files where there are 151 | some empty columns. 152 | 153 | *toinitialcap* – to go along with base R’s tolower() and toupper(), 154 | capitalizes the first letter of each word in a string. Note: base R 155 | 3.2.0 now has tools::toTitleCase() function. 156 | 157 | *streaks* – find winning (or other) streaks in a vector of data, 158 | slightly modified function from [Exploring Baseball Data with 159 | R](https://baseballwithr.wordpress.com/2014/07/07/team-streaks-part-i-2/). 160 | 161 | *strings\_to\_ordered\_factors* – turn a vector of character strings 162 | into an ordered factor, keeping the original order. Helpful if x-axis 163 | order is important when visualizing data. 164 | 165 | *table\_sorted* – get frequency table sorted by frequency descending. 166 | 167 | *unlibrary* – because it can be difficult to remember that 168 | detach(“package:mypackagename”, unload=TRUE) or 169 | unloadNamespace(“mypackagename”) are the opposites of 170 | library(“mypackagename”). 171 | 172 | *varname2string* – takes string and returns value of an object with that 173 | name (there’s also string2varname, which does the reverse) 174 | 175 | *write\_textfile* – write an object containing character string data to 176 | a text file. 177 | 178 | To see a complete list of available function and links to their help 179 | files, run 180 | 181 | ``` r 182 | help(package = "rmiscutils") 183 | ``` 184 | -------------------------------------------------------------------------------- /README.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | output: 3 | md_document: 4 | variant: markdown_github 5 | --- 6 | 7 | 8 | 9 | ```{r, echo = FALSE} 10 | knitr::opts_chunk$set( 11 | collapse = TRUE, 12 | comment = "#>", 13 | fig.path = "README-" 14 | ) 15 | ``` 16 | 17 | This package is a collection of simple R functions that I've either written or discovered over the years that I've found useful and like to re-use. In some cases, these functions are just thin wrappers around other functions but the syntax is easier for me to remember. 18 | 19 | This is a work in progress. 20 | 21 | To install, you need to have the devtools package on your system (if you don't have it, install that with install.packages("devtools") ) and then run 22 | 23 | ```{r, eval = FALSE} 24 | devtools::install_github("smach/rmiscutils") 25 | ``` 26 | 27 | Some of the tasks that functions in this package accomplish: 28 | 29 | 30 | Add a row to a dataframe with the format 31 | ```{r, eval = FALSE} 32 | add_row(mydf, col1 = 4, col2 = 7, col3="A") 33 | ``` 34 | `add_row` 35 | 36 | Add a row to a dataframe with the format 37 | ```{r, eval = FALSE} 38 | add_row_from_list(iris, list(5.1, 3.5, 1.4, 0.2, "setosa")) 39 | ``` 40 | `add_row_from_list` 41 | 42 | Calculate percentages from selected data frame columns by row, and add new columns with that data. Designed for election results. `add_pct_cols_to_dataframe` 43 | 44 | Calculate the statistical mode of a vector (which base R oddly does not do). 45 | `mymode` 46 | 47 | Capitalizes the first letter of each word in a string. (Note: base R 3.2.0 subsequently included the `tools::toTitleCase(`) function, but toinitialcap has the advantage of naming consistency with base R's `tolower` and `toupper`). 48 | `toinitialcap` -- to go along with base R's tolower() and toupper(), 49 | 50 | Convert all NA values in a data frame to zeroes. 51 | `na2zero` 52 | 53 | Convert only NA values to zeroes in data frame columns that are numeric or integers. Uses for loops, so may be slow for large data frames. 54 | `na2zero2` 55 | 56 | Convert character strings containing numbers with commas into numbers. 57 | `numbers_with_commas` 58 | 59 | Convert a vector of character strings into an ordered factor, keeping the original order. Helpful if x-axis order is important when visualizing data. (Created before the forcats package). 60 | `strings_to_ordered_factors` 61 | 62 | Create a frequency table sorted by descending frequency. (Would probably use a version of `janitor::tabyl` today) 63 | `table_sorted` 64 | 65 | Find winning candidates in a spreadsheet or data frame of election results. `elec_find_winner` 66 | 67 | Find winning (or other) streaks in a vector of data. This is a slightly modified function from [Exploring Baseball Data with R](https://baseballwithr.wordpress.com/2014/07/07/team-streaks-part-i-2/). 68 | `streaks` 69 | 70 | Open the file that allows you to edit the RStudio dropdown list of projects. `edit_project_list()` 71 | 72 | Read a text file into an R variable as a single character string. 73 | `read_textfile` 74 | 75 | Rename a single data frame column using format `renamecol(mydf, oldcolname, newcolname)` 76 | `renamecol` 77 | 78 | Remove columns from a data frame where _all_ values are NA. Useful when importing spreadsheets or CSV files where there are some empty columns. 79 | `removecolsAllNA` 80 | 81 | Unload a package from current working session. Because it can be difficult to remember that `detach("package:mypackagename", unload=TRUE)` or `unloadNamespace("mypackagename")` are the opposites of `library("mypackagename")`. 82 | `unlibrary` 83 | 84 | Write an object containing character string data to a text file. 85 | `write_textfile` 86 | 87 | From a character string, return the value of an object with that name (there's also string2varname, which does the reverse) 88 | `varname2string` 89 | 90 | To see a complete list of available function and links to their help files, run 91 | 92 | ```{r, eval = FALSE} 93 | help(package = "rmiscutils") 94 | ``` 95 | 96 | ## Some of the package's functions by function name: 97 | 98 | *add_pct_cols_to_dataframe* -- designed for election results, will calculate percentages from selected columns by row and add new columns with that data. 99 | 100 | *add_row* -- add a row to a dataframe with the format 101 | ```{r, eval = FALSE} 102 | add_row(mydf, col1 = 4, col2 = 7, col3="A") 103 | ``` 104 | Thanks to Hadely Wickham for that function idea. 105 | 106 | *add_row_from_list* -- add a row to a dataframe with the format 107 | ```{r, eval = FALSE} 108 | add_row_from_list(iris, list(5.1, 3.5, 1.4, 0.2, "setosa")) 109 | ``` 110 | Thanks to Jennifer Bryan for that function idea. 111 | 112 | *edit_project_list* -- opens the file that controls RStudio's dropdown project list. 113 | 114 | *mymode* -- calculates the statistical mode of a vector, which base R oddly does not do. 115 | 116 | *na2zero* -- turn all NA values in a data frame to zeroes. 117 | 118 | *na2zero2* -- turns only NA values to zeroes in data frame columns that are numeric or integers. Uses for loops, so may be slow for large data frames. 119 | 120 | *numbers_with_commas* -- easily turn character strings containing numbers with commas into numbers. 121 | 122 | *read_textfile* -- read a text file into an R variable as a single character string. 123 | 124 | *renamecol* -- rename a single column in a dataframe using format renamecol(mydf, oldcolname, newcolname) 125 | 126 | *removecolsAllNA* -- remove columns from a data frame where _all_ values are NA. Useful when importing spreadsheets or CSV files where there are some empty columns. 127 | 128 | *toinitialcap* -- to go along with base R's tolower() and toupper(), capitalizes the first letter of each word in a string. Note: base R 3.2.0 now has tools::toTitleCase() function. 129 | 130 | *streaks* -- find winning (or other) streaks in a vector of data, slightly modified function from [Exploring Baseball Data with R](https://baseballwithr.wordpress.com/2014/07/07/team-streaks-part-i-2/). 131 | 132 | *strings_to_ordered_factors* -- turn a vector of character strings into an ordered factor, keeping the original order. Helpful if x-axis order is important when visualizing data. 133 | 134 | *table_sorted* -- get frequency table sorted by frequency descending. 135 | 136 | *unlibrary* -- because it can be difficult to remember that detach("package:mypackagename", unload=TRUE) or unloadNamespace("mypackagename") are the opposites of library("mypackagename"). 137 | 138 | *varname2string* -- takes string and returns value of an object with that name (there's also string2varname, which does the reverse) 139 | 140 | *write_textfile* -- write an object containing character string data to a text file. 141 | 142 | To see a complete list of available function and links to their help files, run 143 | 144 | ```{r, eval = FALSE} 145 | help(package = "rmiscutils") 146 | ``` 147 | --------------------------------------------------------------------------------