10/13/2017 - 4:32 PM

Match Counter

[Match Counter (by target column)] Function returning a data frame summarising the counts and percentages of row-by-row identical values across the columns of a data frame. Pass a data frame containing some columns including a "target" column - the "target" column is the main column that you want to compare with other columns. Pass the arguments in "dplyr" style, i.e. no need to put column names in quotes. #R

match_counter <- function(df,target){
  arguments <- as.list(
  targ <- deparse(substitute(target)) #variable to string

#Produce a data frame of all columns on whether they match values of target column
  df %>%
    mutate_all(funs(.==eval(parse(text=targ)))) %>%
    colSums(na.rm = TRUE) %>% data.frame() %>%
    rownames_to_column() -> matches 
  names(matches)[2] <- "counts" #rename column as "counts"
  matches$counts[matches$rowname==targ] -> periods #Count number of periods
  matches %>% mutate(prop=counts/periods) %>% #Create proportion column
    select("Variable"=rowname,"Counts"=counts, "Percentage"=prop)