R/assign.score.bin.R

Defines functions assign.score.bin

#' Assign Score Values to Sample Data
#'
#' This function assigns the score value based on defined bins in the scorecard
#' to each characteristic to the the sample data and adds the suffix "_score" 
#' to the character.
#' 
#'
#' @param character vector of names
#' @param df_scorecard mapping data.frame for values
#' @param df_work_sample data.frame where value is applied
#' @return The sum of x and y
#' 
#'
assign.score.bin <- function(character, df_scorecard, df_work_sample) {
	# Create the new var names '..._score'
	character_score <- paste0(quo_name(character), "_score")
	
	# cut() function is producing factors. To recode the factors (classification) 
	# back to the respective Score value create a vector with Score values. This mapping 
	# has to be done to prevent errors occuring because of duplicated score values
	vec_score <-pull(df_scorecard %>%
							filter(characteristics == !!character) %>%
							select(Score))
	
	df_work_sample %>%
	  mutate(classification := as.numeric(
	  	# get values as vector of corresponding column in the dataset
	    cut(
	    	pull(df_work_sample %>% select(!!character)),
	      breaks = c(pull(df_scorecard %>%
	        filter(characteristics == !!character) %>%
	        select(u)), 99999),
	      right = FALSE
	    )
	  )) %>%
		# assign the Score value matching the classification
	  mutate(!!character_score := vec_score[classification]) %>%
	  select(all_of(character_score))
}
irisweyermenkhoff/toyota-idv-functions documentation built on March 4, 2020, 9:57 a.m.