content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title External Collaboration Summary
#'
#' @description
#' Provides an overview analysis of 'External Collaboration'.
#' Returns a stacked bar plot of internal and external collaboration.
#' Additional options available to return a summary table.
#'
#' @inheritParams create_stacked
#' @inherit create_stacked return
#'
#' @family Visualization
#' @family External Collaboration
#'
#' @examples
#' # Return a plot
#' external_sum(sq_data, hrvar = "LevelDesignation")
#'
#' # Return summary table
#' external_sum(sq_data, hrvar = "LevelDesignation", return = "table")
#'
#' @export
external_sum <- function(data,
hrvar = "Organization",
mingroup = 5,
stack_colours = c("#1d327e", "#1d7e6a"),
return = "plot"){
# Calculate Internal / External Collaboration time
plot_data <- data %>% mutate(Internal_hours= Collaboration_hours - Collaboration_hours_external) %>% mutate(External_hours= Collaboration_hours_external)
# Plot Internal / External Collaboration time by Organization
plot_data %>% create_stacked(hrvar = hrvar, metrics = c("Internal_hours", "External_hours"), plot_title = "Internal and External Collaboration Hours", stack_colours = stack_colours, mingroup = mingroup, return = return)
}
#' @rdname external_sum
#' @export
external_summary <- external_sum
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/external_sum.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Extract HR attribute variables
#'
#' @description
#' This function uses a combination of variable class,
#' number of unique values, and regular expression matching
#' to extract HR / organisational attributes from a data frame.
#'
#' @param data A data frame to be passed through.
#' @param max_unique A numeric value representing the maximum
#' number of unique values to accept for an HR attribute. Defaults to 50.
#' @param exclude_constants Logical value to specify whether single-value HR
#' attributes are to be excluded. Defaults to `TRUE`.
#'
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"names"`
#' - `"vars"`
#'
#' See `Value` for more information.
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"names"`: character vector identifying all the names of HR variables
#' present in the data.
#' - `"vars"`: data frame containing all the columns of HR variables present
#' in the data.
#'
#' @family Support
#' @family Data Validation
#'
#' @examples
#' sq_data %>% extract_hr(return = "names")
#'
#' sq_data %>% extract_hr(return = "vars")
#'
#' @export
extract_hr <- function(data,
max_unique = 50,
exclude_constants = TRUE,
return = "names"){
if(exclude_constants == TRUE){
min_unique = 1
} else if (exclude_constants == FALSE){
min_unique = 0
}
hr_var <-
data %>%
dplyr::select_if(~(is.character(.) | is.logical(.) | is.factor(.))) %>%
dplyr::select_if(~(dplyr::n_distinct(.) < max_unique)) %>%
dplyr::select_if(~(dplyr::n_distinct(.) > min_unique)) %>% # Exc constants
dplyr::select_if(~!all(is_date_format(.))) %>%
names() %>%
.[.!= "WorkingStartTimeSetInOutlook"] %>%
.[.!= "WorkingEndTimeSetInOutlook"] %>%
.[.!= "WorkingDaysSetInOutlook"]
if(return == "names"){
return(hr_var)
} else if(return == "vars"){
return(dplyr::select(data, tidyselect::all_of(hr_var)))
} else {
stop("Invalid input for return")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/extract_hr.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Flag unusual high collaboration hours to after-hours collaboration
#' hours ratio
#'
#' @description This function flags persons who have an unusual ratio
#' of collaboration hours to after-hours collaboration hours.
#' Returns a character string by default.
#'
#' @template ch
#'
#' @import dplyr
#'
#' @param data A data frame containing a Person Query.
#' @param threshold Numeric value specifying the threshold for flagging.
#' Defaults to 30.
#' @param return String to specify what to return. Options include:
#' - `"message"`
#' - `"text"`
#' - `"data"`
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"message"`: message in the console containing diagnostic summary
#' - `"text"`: string containing diagnotic summary
#' - `"data"`: data frame. Person-level data with flags on unusually high or
#' low ratios
#'
#' @family Data Validation
#'
#' @examples
#' flag_ch_ratio(sq_data)
#'
#'
#' data.frame(PersonId = c("Alice", "Bob"),
#' Collaboration_hours = c(30, 0.5),
#' After_hours_collaboration_hours = c(0.5, 30)) %>%
#' flag_ch_ratio()
#'
#' @export
flag_ch_ratio <- function(data, threshold = c(1, 30), return = "message"){
min_thres <- min(threshold, na.rm = TRUE)
max_thres <- max(threshold, na.rm = TRUE)
## Check for high collab hours but lower afterhour collab hours
## Because of faulty outlook settings
ch_summary <-
data %>%
group_by(PersonId) %>%
summarise_at(vars(Collaboration_hours, After_hours_collaboration_hours), ~mean(.)) %>%
mutate(CH_ratio = Collaboration_hours / After_hours_collaboration_hours) %>%
arrange(desc(CH_ratio)) %>%
mutate(CH_FlagLow = ifelse(CH_ratio < min_thres, TRUE, FALSE),
CH_FlagHigh = ifelse(CH_ratio > max_thres, TRUE, FALSE),
CH_Flag = ifelse(CH_ratio > max_thres | CH_ratio < min_thres, TRUE, FALSE))
## Percent of people with high collab hours + low afterhour collab hours
CHFlagN <- sum(ch_summary$CH_Flag, na.rm = TRUE)
CHFlagProp <- mean(ch_summary$CH_Flag, na.rm = TRUE)
CHFlagProp2 <- paste(round(CHFlagProp * 100), "%") # Formatted
CHFlagMessage_Warning <- paste0("[Warning] The ratio of after-hours collaboration to total collaboration hours is outside the expected threshold for ", CHFlagN, " employees (", CHFlagProp2, " of the total).")
CHFlagMessage_Pass_Low <- paste0("[Pass] The ratio of after-hours collaboration to total collaboration hours is outside the expected threshold for only ", CHFlagN, " employees (", CHFlagProp2, " of the total).")
CHFlagMessage_Pass_Zero <- paste0("[Pass] The ratio of after-hours collaboration to total collaboration hours falls within the expected threshold for all employees.")
CHFlagLowN <- sum(ch_summary$CH_FlagLow, na.rm = TRUE)
CHFlagLowProp <- mean(ch_summary$CH_FlagLow, na.rm = TRUE)
CHFlagLowProp2 <- paste(round(CHFlagLowProp * 100), "%") # Formatted
CHFlagLowMessage <- paste0("- ", CHFlagLowN, " employees (", CHFlagLowProp2,
") have an unusually low after-hours collaboration")
CHFlagHighN <- sum(ch_summary$CH_FlagHigh, na.rm = TRUE)
CHFlagHighProp <- mean(ch_summary$CH_FlagHigh, na.rm = TRUE)
CHFlagHighProp2 <- paste(round(CHFlagHighProp * 100), "%") # Formatted
CHFlagHighMessage <- paste0("- ", CHFlagHighN, " employees (", CHFlagHighProp2 , ") have an unusually high after-hours collaboration (relative to weekly collaboration hours)")
if(CHFlagProp >= .05){
CHFlagMessage <- paste(CHFlagMessage_Warning, CHFlagHighMessage, CHFlagLowMessage, sep = "\n")
} else if(CHFlagProp < .05 & CHFlagProp2 > 0){
CHFlagMessage <- paste(CHFlagMessage_Pass_Low, CHFlagHighMessage, CHFlagLowMessage, sep = "\n")
} else if(CHFlagProp==0){
CHFlagMessage <- CHFlagMessage_Pass_Zero
}
## Print diagnosis
## Should implement options to return the PersonIds or a full data frame
if(return == "message"){
message(CHFlagMessage)
} else if(return == "text"){
CHFlagMessage
} else if(return == "data") {
ch_summary
} else {
stop("Invalid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/flag_ch_ratio.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Flag Persons with unusually high Email Hours to Emails Sent ratio
#'
#' @description This function flags persons who have an unusual ratio
#' of email hours to emails sent. If the ratio between Email Hours and
#' Emails Sent is greater than the threshold, then observations tied to
#' a `PersonId` is flagged as unusual.
#'
#' @import dplyr
#'
#' @family Data Validation
#'
#' @param data A data frame containing a Person Query.
#' @param threshold Numeric value specifying the threshold for flagging.
#' Defaults to 1.
#'
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"text"`
#' - `"data"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"text"`: string. A diagnostic message.
#' - `"data"`: data frame. Person-level data with those flagged with unusual
#' ratios.
#'
#' @examples
#' flag_em_ratio(sq_data)
#'
#' @export
flag_em_ratio <- function(data, threshold = 1, return = "text"){
## Check for high collab hours but lower afterhour collab hours
## Because of faulty outlook settings
em_summary <-
data %>%
group_by(PersonId) %>%
summarise_at(vars(Email_hours, Emails_sent), ~mean(.)) %>%
mutate(Email_ratio = Email_hours / Emails_sent) %>%
arrange(desc(Email_ratio)) %>%
mutate(Email_Flag = ifelse(Email_ratio > threshold, TRUE, FALSE))
## Percent of people with high collab hours + low afterhour collab hours
EmailFlagN <- sum(em_summary$Email_Flag, na.rm = TRUE)
EmailFlagProp <- mean(em_summary$Email_Flag, na.rm = TRUE)
EmailFlagProp2 <- paste(round(EmailFlagProp * 100), "%") # Formatted
EmailFlagMessage <- paste0(EmailFlagProp2, " (", EmailFlagN, ") ",
"of the population have an unusually high email hours to emails sent ratio.")
if(return == "text"){
EmailFlagMessage
} else if(return == "data"){
em_summary
} else {
stop("Invalid input to `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/flag_em_ratio.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Warn for extreme values by checking against a threshold
#'
#' @description
#' This is used as part of data validation to check if there are extreme values
#' in the dataset.
#'
#' @param data A Standard Person Query dataset in the form of a data frame.
#' @param metric A character string specifying the metric to test.
#' @param person A logical value to specify whether to calculate
#' person-averages. Defaults to `TRUE` (person-averages calculated).
#' @param threshold Numeric value specifying the threshold for flagging.
#' @param mode String determining mode to use for identifying extreme values.
#' - `"above"`: checks whether value is great than the threshold (default)
#' - `"equal"`: checks whether value is equal to the threshold
#' - `"below"`: checks whether value is below the threshold
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"text"`
#' - `"message"`
#' - `"table"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"text"`: string. A diagnostic message.
#' - `"message"`: message on console. A diagnostic message.
#' - `"table"`: data frame. A person-level table with `PersonId` and the
#' extreme values of the selected metric.
#'
#' @family Data Validation
#'
#' @import dplyr
#'
#' @examples
#' # The threshold values are intentionally set low to trigger messages.
#' flag_extreme(sq_data, "Email_hours", threshold = 15)
#'
#' # Return a summary table
#' flag_extreme(sq_data, "Email_hours", threshold = 15, return = "table")
#'
#' # Person-week level
#' flag_extreme(sq_data, "Email_hours", person = FALSE, threshold = 15)
#'
#' # Check for values equal to threshold
#' flag_extreme(sq_data, "Email_hours", person = TRUE, mode = "equal", threshold = 0)
#'
#' # Check for values below threshold
#' flag_extreme(sq_data, "Email_hours", person = TRUE, mode = "below", threshold = 5)
#'
#'
#' @export
flag_extreme <- function(data,
metric,
person = TRUE,
threshold,
mode = "above",
return = "message"){
## Define relational term/string and input checks
if(mode == "above"){
rel_str <- " exceeds "
} else if(mode == "equal"){
rel_str <- " are equal to "
} else if(mode == "below"){
rel_str <- " are less than "
} else {
stop("invalid input to `mode`")
}
## Data frame containing the extreme values
if(person == TRUE){
extreme_df <-
data %>%
rename(metric = !!sym(metric)) %>%
group_by(PersonId) %>%
summarise_at(vars(metric), ~mean(.)) %>%
# Begin mode chunk
{
if(mode == "above"){
filter(., metric > threshold)
} else if(mode == "equal"){
filter(., metric == threshold)
} else if(mode == "below"){
filter(., metric < threshold)
}
} %>%
rename(!!sym(metric) := "metric")
} else if(person == FALSE){
extreme_df <-
data %>%
rename(metric = !!sym(metric)) %>%
# Begin mode chunk
{
if(mode == "above"){
filter(., metric > threshold)
} else if(mode == "equal"){
filter(., metric == threshold)
} else if(mode == "below"){
filter(., metric < threshold)
}
} %>%
rename(!!sym(metric) := "metric")
}
## Clean names for pretty printing
metric_nm <- metric %>% us_to_space() %>% camel_clean()
## Define MessageLevel
if(person == TRUE){
MessageLevel <- " persons where their average "
} else if(person == FALSE){
MessageLevel <- " rows where their value of "
}
## Define FlagMessage
if(nrow(extreme_df) == 0){
FlagMessage <-
paste0("[Pass] There are no",
MessageLevel,
metric_nm,
rel_str,
threshold, ".")
} else {
FlagMessage <-
paste0("[Warning] There are ",
nrow(extreme_df),
MessageLevel,
metric_nm,
rel_str,
threshold, ".")
}
if(return == "text"){
FlagMessage
} else if(return == "message"){
message(FlagMessage)
} else if(return == "table"){
extreme_df
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/flag_extreme.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Flag unusual outlook time settings for work day start and end time
#'
#' @description This function flags unusual outlook calendar settings for
#' start and end time of work day.
#'
#' @import dplyr
#'
#' @param data A data frame containing a Person Query.
#' @param threshold A numeric vector of length two, specifying the hour
#' threshold for flagging. Defaults to c(4, 15).
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"text"` (default)
#' - `"message"`
#' - `"data"`
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"text"`: string. A diagnostic message.
#' - `"message"`: message on console. A diagnostic message.
#' - `"data"`: data frame. Data where flag is present.
#'
#' See `Value` for more information.
#'
#' @family Data Validation
#'
#' @examples
#' # Demo with `dv_data`
#' flag_outlooktime(dv_data)
#'
#' # Example where Outlook Start and End times are imputed
#' spq_df <- sq_data
#'
#' spq_df$WorkingStartTimeSetInOutlook <- "6:30"
#'
#' spq_df$WorkingEndTimeSetInOutlook <- "23:30"
#'
#' # Return a message
#' flag_outlooktime(spq_df, threshold = c(5, 13))
#'
#' # Return data
#' flag_outlooktime(spq_df, threshold = c(5, 13), return = "data")
#'
#' @export
flag_outlooktime <- function(data, threshold = c(4, 15), return = "message"){
# pad_times <- function(x){
# if(nchar(x) == 1){
# x <- paste0("0", x, "00")
# } else if(nchar(x) == 2){
# x <- paste0(x, "00")
# } else if(nchar(x) == 3){
# x <- paste0("0", x)
# } else {
# x
# }
# }
#
# pad_times <- Vectorize(pad_times)
## Clean `WorkingStartTimeSetInOutlook`
if(any(grepl(pattern = "\\d{1}:\\d{1,2}", x = data$WorkingStartTimeSetInOutlook))){
# Pad two zeros and keep last five characters
data$WorkingStartTimeSetInOutlook <-
paste0("00", data$WorkingStartTimeSetInOutlook) %>%
substr(start = nchar(.) - 4, stop = nchar(.))
}
## Clean `WorkingEndTimeSetInOutlook`
if(any(grepl(pattern = "\\d{1}:\\d{1,2}", x = data$WorkingEndTimeSetInOutlook))){
# Pad two zeros and keep last five characters
data$WorkingEndTimeSetInOutlook <-
paste0("00", data$WorkingEndTimeSetInOutlook) %>%
substr(start = nchar(.) - 4, stop = nchar(.))
}
if(
any(
!grepl(pattern = "\\d{1,2}:\\d{1,2}", x = data$WorkingStartTimeSetInOutlook) |
!grepl(pattern = "\\d{1,2}:\\d{1,2}", x = data$WorkingEndTimeSetInOutlook)
)
){
stop("Please check data format for `WorkingStartTimeSetInOutlook` or `WorkingEndTimeSetInOutlook.\n
These variables must be character vectors, and have the format `%H:%M`, such as `07:30` or `23:00`.")
}
clean_times <- function(x){
out <- gsub(pattern = ":", replacement = "", x = x)
# out <- pad_times(out)
strptime(out, format = "%H%M")
}
flagged_data <-
data %>%
# mutate_at(vars(WorkingStartTimeSetInOutlook, WorkingEndTimeSetInOutlook), ~clean_times(.)) %>%
mutate_at(vars(WorkingStartTimeSetInOutlook, WorkingEndTimeSetInOutlook), ~gsub(pattern = ":", replacement = "", x = .)) %>%
mutate_at(vars(WorkingStartTimeSetInOutlook, WorkingEndTimeSetInOutlook), ~strptime(., format = "%H%M")) %>%
mutate(WorkdayRange = as.numeric(WorkingEndTimeSetInOutlook - WorkingStartTimeSetInOutlook, units = "hours"),
WorkdayFlag1 = WorkdayRange < threshold[[1]],
WorkdayFlag2 = WorkdayRange > threshold[[2]],
WorkdayFlag = WorkdayRange < threshold[[1]] | WorkdayRange > threshold[[2]]) %>%
select(PersonId, WorkdayRange, WorkdayFlag, WorkdayFlag1, WorkdayFlag2)
## Short working hour settings
FlagN1 <- sum(flagged_data$WorkdayFlag1, na.rm = TRUE)
FlagProp1 <- mean(flagged_data$WorkdayFlag1, na.rm = TRUE)
FlagProp1F <- paste0(round(FlagProp1 * 100, 1), "%") # Formatted
## Long working hour settings
FlagN2 <- sum(flagged_data$WorkdayFlag2, na.rm = TRUE)
FlagProp2 <- mean(flagged_data$WorkdayFlag2, na.rm = TRUE)
FlagProp2F <- paste0(round(FlagProp2 * 100, 1), "%") # Formatted
## Short or long working hoursettings
FlagN <- sum(flagged_data$WorkdayFlag, na.rm = TRUE)
FlagProp <- mean(flagged_data$WorkdayFlag, na.rm = TRUE)
FlagPropF <- paste0(round(FlagProp * 100, 1), "%") # Formatted
## Flag Messages
Warning_Message <- paste0("[Warning] ", FlagPropF, " (", FlagN, ") ", "of the person-date rows in the data have extreme Outlook settings.")
Pass_Message1 <- paste0("[Pass] Only ", FlagPropF, " (", FlagN, ") ", "of the person-date rows in the data have extreme Outlook settings.")
Pass_Message2 <- paste0("There are no extreme Outlook settings in this dataset (Working hours shorter than ", threshold[[1]], " hours, or longer than ", threshold[[2]], " hours.")
Detail_Message <- paste0(FlagProp1F, " (", FlagN1, ") ", " have an Outlook workday shorter than ", threshold[[1]], " hours, while ",
FlagProp2F, " (", FlagN2, ") ", "have a workday longer than ", threshold[[2]], " hours.")
if(FlagProp >= .05){
FlagMessage <- paste(Warning_Message, Detail_Message, sep = "\n")
} else if(FlagProp < .05 & FlagProp > 0){
FlagMessage <- paste(Pass_Message1, Detail_Message, sep = "\n")
} else if(FlagProp==0){
FlagMessage <- Pass_Message2
}
## Print diagnosis
## Should implement options to return the PersonIds or a full data frame
if(return == "text"){
FlagMessage
} else if(return == "message"){
message(FlagMessage)
} else if(return == "data"){
flagged_data[flagged_data$WorkdayFlag == TRUE,]
} else {
stop("Error: please check inputs for `return`")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/flag_outlooktime.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Compute a Flexibility Index based on the Hourly Collaboration Query
#'
#' @description
#' `r lifecycle::badge('experimental')`
#'
#' Pass an Hourly Collaboration query and compute a Flexibility Index for the
#' entire population. The Flexibility Index is a quantitative measure of the
#' freedom for employees to work at a time of their choice.
#'
#' @details
#' The **Flexibility Index** is a metric that has been developed to quantify and
#' measure flexibility using behavioural data from Viva Insights. Flexibility
#' here refers to the freedom of employees to adopt a working arrangement of
#' their own choice, and more specifically refers to **time** flexibility
#' (_whenever_ I want) as opposed to **geographical** flexibility (_wherever_ I
#' want).
#'
#' The **Flexibility Index** is a score between 0 and 1, and is calculated based
#' on three component measures:
#'
#' - `ChangeHours`: this represents the freedom to define work start and end
#' time. Teams that embrace flexibility allow members to start and end their
#' workday at different times.
#'
#' - `TakeBreaks`: this represents the freedom define one's own schedule. In
#' teams that embrace flexibility, some members will choose to organize / split
#' their day in different ways (e.g. take a long lunch-break, disconnect in the
#' afternoon and reconnect in the evening, etc.).
#'
#' - `ControlHours`: this represents the freedom to switch off. Members who
#' choose alternative arrangements should be able to maintain a workload that is
#' broadly equivalent to those that follow standard arrangements.
#'
#' The **Flexibility Index** returns with one single score for each person-week,
#' plus the **three** sub-component binary variables (`TakeBreaks`,
#' `ChangeHours`, `ControlHours`). At the person-week level, each score can only
#' have the values 0, 0.33, 0.66, and 1. The Flexibility Index should only be
#' interpreted as a **group** of person-weeks, e.g. the average Flexibility
#' Index of a team of 6 over time, where the possible values would range from 0
#' to 1.
#'
#' @section Context:
#' The central feature of flexible working arrangements is
#' that it is the employee rather the employer who chooses the working
#' arrangement. _Observed flexibility_ serves as a proxy to assess whether a
#' flexible working arrangement are in place. The Flexibility Index is an
#' attempt to create such a proxy for quantifying and measuring flexibility,
#' using behavioural data from Viva Insights.
#'
#' @section Recurring disconnection time:
#' The key component of `TakeBreaks` in the Flexibility Index is best
#' interpreted as 'recurring disconnection time'. This denotes an hourly block
#' where there is consistently no activity occurring throughout the week. Note
#' that this applies a stricter criterion compared to the common definition of
#' a break, which is simply a time interval where no active work is being
#' done, and thus the more specific terminology 'recurring disconnection time'
#' is preferred.
#'
#' @param data Hourly Collaboration query to be passed through as data frame.
#'
#' @param hrvar A string specifying the HR attribute to cut the data by.
#' Defaults to NULL. This only affects the function when "table" is returned.
#'
#' @param signals Character vector to specify which collaboration metrics to
#' use:
#' - a combination of signals, such as `c("email", "IM")` (default)
#' - `"email"` for emails only
#' - `"IM"` for Teams messages only
#' - `"unscheduled_calls"` for Unscheduled Calls only
#' - `"meetings"` for Meetings only
#'
#' @param active_threshold A numeric value specifying the minimum number of
#' signals to be greater than in order to qualify as _active_. Defaults to 0.
#'
#' @param start_hour A character vector specifying starting hours, e.g. `"0900"`
#'
#' @param end_hour A character vector specifying end hours, e.g. `"1700"`
#'
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"data"`
#' - `"table"`
#'
#' See `Value` for more information.
#'
#' @param plot_method Character string for determining which plot to return.
#' - `"sample"` plots a sample of ten working pattern
#' - `"common"` plots the ten most common working patterns
#' - `"time"` plots the Flexibility Index for the group over time
#'
#' @param mode String specifying aggregation method for plot. Only applicable
#' when `return = "plot"`. Valid options include:
#' - `"binary"`: convert hourly activity into binary blocks. In the plot, each
#' block would display as solid.
#' - `"prop"`: calculate proportion of signals in each hour over total signals
#' across 24 hours, then average across all work weeks. In the plot, each
#' block would display as a heatmap.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: 'ggplot' object. A random of ten working patterns are displayed,
#' with diagnostic data and the Flexibility Index shown on the plot.
#' - `"data"`: data frame. The original input data appended with the
#' Flexibility Index and the component scores. Can be used with
#' `plot_flex_index()` to recreate visuals found in `flex_index()`.
#' - `"table"`: data frame. A summary table for the metric.
#'
#'
#' @import dplyr
#' @importFrom data.table ":=" "%like%" "%between%"
#'
#' @examples
#' \donttest{
#' # Create a sample small dataset
#' orgs <- c("Customer Service", "Financial Planning", "Biz Dev")
#' em_data <- em_data[em_data$Organization %in% orgs, ]
#'
#' # Examples of how to test the plotting options individually
#' # Sample of 10 work patterns
#' em_data %>%
#' flex_index(return = "plot", plot_method = "sample")
#'
#' # 10 most common work patterns
#' em_data %>%
#' flex_index(return = "plot", plot_method = "common")
#'
#' # Plot Flexibility Index over time
#' em_data %>%
#' flex_index(return = "plot", plot_method = "time")
#'
#' # Return a summary table with the computed Flexibility Index
#' em_data %>%
#' flex_index(hrvar = "Organization", return = "table")
#' }
#'
#' @section Returning the raw data:
#' The raw data containing the computed Flexibility Index can be returned with
#' the following:
#' ```
#' em_data %>%
#' flex_index(return = "data")
#' ```
#'
#' @family Working Patterns
#'
#' @export
flex_index <- function(data,
hrvar = NULL,
signals = c("email", "IM"),
active_threshold = 0,
start_hour = "0900",
end_hour = "1700",
return = "plot",
plot_method = "common",
mode = "binary"){
## Bindings for variables
TakeBreaks <- NULL
ChangeHours <- NULL
ControlHours <- NULL
FlexibilityIndex <- NULL
Signals_Break_hours <- NULL
## Make sure data.table knows we know we're using it
.datatable.aware = TRUE
## Save original
start_hour_o <- start_hour
end_hour_o <- end_hour
## Coerce to numeric, remove trailing zeros
start_hour <- as.numeric(gsub(pattern = "00$", replacement = "", x = start_hour))
end_hour <- as.numeric(gsub(pattern = "00$", replacement = "", x = end_hour))
norm_span <- end_hour - start_hour
## convert to data.table
data2 <-
data %>%
dplyr::mutate(Date = as.Date(Date, format = "%m/%d/%Y")) %>%
data.table::as.data.table() %>%
data.table::copy()
## Text replacement only for allowed values
if(any(signals %in% c("email", "IM", "unscheduled_calls", "meetings"))){
signal_set <- gsub(pattern = "email", replacement = "Emails_sent", x = signals) # case-sensitive
signal_set <- gsub(pattern = "IM", replacement = "IMs_sent", x = signal_set)
signal_set <- gsub(pattern = "unscheduled_calls", replacement = "Unscheduled_calls", x = signal_set)
signal_set <- gsub(pattern = "meetings", replacement = "Meetings", x = signal_set)
} else {
stop("Invalid input for `signals`.")
}
## Create 24 summed `Signals_sent` columns
signal_cols <- purrr::map(0:23, ~combine_signals(data, hr = ., signals = signal_set))
signal_cols <- bind_cols(signal_cols)
## Use names for matching
input_var <- names(signal_cols)
## Signals sent by Person and Date
signals_df <-
data2 %>%
.[, c("PersonId", "Date")] %>%
cbind(signal_cols)
## Save original `signals_df` before manipulating ------------------------
## Rename `Signals_sent` columns to prevent conflict
signals_df_o <- signals_df %>%
purrr::set_names(
nm = gsub(x = names(.),
replacement = "_ori_",
pattern = "_sent_")
)
## Signal label
sig_label <- ifelse(length(signal_set) > 1, "Signals_sent", signal_set)
## Create binary variable 0 or 1
num_cols <- names(which(sapply(signals_df, is.numeric))) # Get numeric columns
## Create Signals Total and binary values
signals_df <-
signals_df %>%
data.table::as.data.table() %>%
# active_threshold: minimum signals to qualify as active
.[, (num_cols) := lapply(.SD, function(x) ifelse(x > active_threshold, 1, 0)), .SDcols = num_cols] %>%
.[, ("Signals_Total") := apply(.SD, 1, sum), .SDcols = input_var]
## Classify PersonId-Signal data by time of day
WpA_classify <-
signals_df %>%
tidyr::gather(!!sym(sig_label), sent, -PersonId, -Date, -Signals_Total) %>%
data.table::as.data.table()
WpA_classify[, StartEnd := gsub(pattern = "[^[:digit:]]", replacement = "", x = get(sig_label))]
WpA_classify[, Start := as.numeric(substr(StartEnd, start = 1, stop = 2))]
WpA_classify[, End := as.numeric(substr(StartEnd, start = 3, stop = 4))]
WpA_classify[, Before_start := Start < (start_hour)] # Earlier than start hour
WpA_classify[, After_end := End > (end_hour)] # Later than start hour
WpA_classify[, Within_hours := (Start >= start_hour & End <= end_hour)]
WpA_classify[, HourType := NA_character_]
WpA_classify[After_end == TRUE, HourType := "After_end"]
WpA_classify[Before_start == TRUE, HourType := "Before_start"]
WpA_classify[Within_hours == TRUE, HourType := "Within_hours"]
WpA_classify <-
WpA_classify[, c("PersonId", "Date", "Signals_Total", "HourType", "sent")] %>%
.[, .(sent = sum(sent)), by = c("PersonId", "Date", "Signals_Total", "HourType")] %>%
tidyr::spread(HourType, sent) %>%
left_join(WpA_classify %>% ## Calculate first and last activity for day_span
filter(sent>0) %>%
group_by(PersonId,Date) %>%
summarise(First_signal = min(Start),
Last_signal = max(End),
.groups = "drop_last"),
by = c("PersonId","Date")) %>%
mutate(Day_Span = Last_signal-First_signal,
Signals_Break_hours = Day_Span-Signals_Total) %>%
select(-Signals_Total)
## hrvar treatment
if(is.null(hrvar)){
hr_dt <- data2[, c("PersonId", "Date")]
hr_dt <- hr_dt[, Total := "Total"]
hrvar <- "Total"
hr_dt <- as.data.frame(hr_dt)
} else {
temp_str <- c("PersonId", "Date", hrvar)
# hr_dt <- data2[, ..temp_str] # double dot prefix
hr_dt <-
data2 %>%
as.data.frame() %>%
select(temp_str)
}
## Bind calculated columns with original Signals df
calculated_data <-
WpA_classify %>%
left_join(signals_df, by = c("PersonId","Date")) %>%
left_join(hr_dt, by = c("PersonId","Date")) %>%
left_join(signals_df_o, by = c("PersonId","Date")) %>%
filter(Signals_Total >= 3) %>% # At least 3 signals required
## Additional calculations for Flexibility Index
mutate(TakeBreaks = (Signals_Break_hours > 0),
ChangeHours = (First_signal != start_hour),
ControlHours = (Day_Span <= norm_span)) %>%
mutate(FlexibilityIndex = select(., TakeBreaks, ChangeHours, ControlHours) %>%
apply(1, mean))
## Plot return
sig_label_ <- paste0(sig_label, "_")
## Summary Table for Return
## Applies groups
returnTable <-
calculated_data %>%
group_by(!!sym(hrvar)) %>%
summarise_at(vars(TakeBreaks, ChangeHours, ControlHours),
~mean(.), .groups = "drop_last") %>%
mutate(FlexibilityIndex =
select(., TakeBreaks, ChangeHours, ControlHours) %>%
apply(1, mean))
## Main plot
if(return == "plot"){
plot_flex_index(data = calculated_data,
sig_label = sig_label_,
start_hour = start_hour,
end_hour = end_hour,
method = plot_method,
mode = mode)
} else if(return == "data"){
calculated_data
} else if(return == "table"){
returnTable
} else {
stop("Check input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/flex_index.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Sample Group-to-Group dataset
#'
#' @description
#' A demo dataset representing a Group-to-Group Query. The grouping
#' organizational attribute used here is `Organization`, where the variable have
#' been prefixed with `TimeInvestors_` and `Collaborators_` to represent the
#' direction of collaboration.
#'
#' @family Data
#' @family Network
#'
#' @return data frame.
#'
#' @format A data frame with 1417 rows and 7 variables:
#' \describe{
#' \item{TimeInvestors_Organization}{ }
#' \item{Collaborators_Organization}{ }
#' \item{Date}{ }
#' \item{Meetings}{ }
#' \item{Meeting_hours}{ }
#' \item{Email_hours}{ }
#' \item{Collaboration_hours}{ }
#'
#' ...
#' }
"g2g_data"
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/g2g_data.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Generate HTML report with list inputs
#'
#' @description
#' This is a support function using a list-pmap workflow to
#' create a HTML document, using RMarkdown as the engine.
#'
#' @author Martin Chan <martin.chan@@microsoft.com>
#'
#' @param title Character string to specify the title of the chunk.
#' @param filename File name to be used in the exported HTML.
#' @param outputs A list of outputs to be added to the HTML report.
#' Note that `outputs`, `titles`, `echos`, and `levels` must have the same
#' length
#' @param titles A list/vector of character strings to specify the title of the
#' chunks.
#' @param subheaders A list/vector of character strings to specify the
#' subheaders for each chunk.
#' @param echos A list/vector of logical values to specify whether to display
#' code.
#' @param levels A list/vector of numeric value to specify the header level of
#' the chunk.
#' @param theme Character vector to specify theme to be used for the report.
#' E.g. `"united"`, `"default"`.
#' @param preamble A preamble to appear at the beginning of the report, passed
#' as a text string.
#'
#' @importFrom purrr pmap
#' @importFrom purrr reduce
#'
#' @family Reports
#'
#' @section Creating a custom report:
#'
#' Below is an example on how to set up a custom report.
#'
#' The first step is to define the content that will go into a report and assign
#' the outputs to a list.
#'
#' ```
#' # Step 1: Define Content
#' output_list <-
#' list(sq_data %>% workloads_summary(return = "plot"),
#' sq_data %>% workloads_summary(return = "table")) %>%
#' purrr::map_if(is.data.frame, create_dt)
#' ```
#'
#' The next step is to add a list of titles for each of the objects on the list:
#'
#' ```
#' # Step 2: Add Corresponding Titles
#' title_list <- c("Workloads Summary - Plot", "Workloads Summary - Table")
#' n_title <- length(title_list)
#' ```
#' The final step is to run `generate_report()`. This can all be wrapped within
#' a function such that the function can be used to generate a HTML report.
#' ```
#' # Step 3: Generate Report
#' generate_report(title = "My First Report",
#' filename = "My First Report",
#' outputs = output_list,
#' titles = title_list,
#' subheaders = rep("", n_title),
#' echos = rep(FALSE, n_title
#' ```
#' @return
#' An HTML report with the same file name as specified in the arguments is
#' generated in the working directory. No outputs are directly returned by the
#' function.
#'
#' @export
generate_report <- function(title = "My minimal HTML generator",
filename = "minimal_html",
outputs = output_list,
titles,
subheaders,
echos,
levels,
theme = "united",
preamble = ""){
## Title of document
title_chr <- paste0('title: \"', title, '\"')
## chunk loopage
## merged to create `chunk_merged`
chunk_merged <-
list(output = outputs,
title = titles,
subheader = subheaders,
echo = echos,
level = levels,
id = seq(1, length(outputs))) %>%
purrr::pmap(function(output, title, subheader, echo, level, id){
generate_chunks(level = level,
title = title,
subheader = subheader,
echo = echo,
object = paste0("outputs[[", id, "]]"))
}) %>%
purrr::reduce(c)
# wpa_logo <- system.file("logos/logo.PNG", package = "wpa")
## markdown object
markobj <- c('---',
title_chr <- paste0('title: \"', title, '\"'),
'output: ',
' html_document:',
paste0(' theme: ', theme),
# ' theme: united',
' toc: true',
' toc_float:',
' collapsed: false',
' smooth_scroll: true',
'---',
# paste0(''),
'',
preamble,
'',
chunk_merged)
writeLines(markobj, paste0(filename, ".Rmd"))
rmarkdown::render(paste0(filename, ".Rmd"))
## Load in browser
utils::browseURL(paste0(filename, ".html"))
## Deletes specified files
unlink(c(paste0(filename, ".Rmd"),
paste0(filename, ".md")))
}
#' @title Generate chunk strings
#'
#' @description This is used as a supporting function for `generate_report()`
#' and not directly used. `generate_report()`` works by creating a
#' loop structure around generate_chunks(), and binds them together
#' to create a report.
#'
#' @details
#' `generate_chunks()` is primarily a wrapper around paste() functions,
#' to create a structured character vector that will form the individual
#' chunks. No plots 'exist' within the environment of `generate_chunks()`.
#'
#' @param level Numeric value to specify the header level of the chunk.
#' @param title Character string to specify the title of the chunk.
#' @param subheader Character string to specify the subheader of the chunk.
#' @param echo Logical value to specify whether to display code.
#' @param object Character string to specify name of the object to show.
#'
#' @noRd
generate_chunks <- function(level = 3,
title,
subheader = "",
echo = FALSE,
object){
level_hash <- paste(rep('#', level), collapse = "")
obj <- c(paste(level_hash, title),
subheader,
paste0('```{r, echo=',
echo,
', fig.height=9, fig.width=12}'),
object,
'```',
' ')
return(obj)
}
#' @title Read preamble
#'
#' @description
#' Read in a preamble to be used within each individual reporting function.
#' Reads from the Markdown file installed with the package.
#'
#' @param path Text string containing the path for the appropriate Markdown file.
#'
#' @return
#' String containing the text read in from the specified Markdown file.
#'
#' @family Support
#' @family Reports
#'
#' @export
read_preamble <- function(path){
full_path <- paste0("/preamble/", path)
complete_path <- paste0(path.package("wpa"), full_path)
text <- suppressWarnings(readLines(complete_path))
return(text)
}
#' Display HTML fragment in RMarkdown chunk, from Markdown text
#'
#' @description
#' This is a wrapper around `markdown::markdownToHTML()`, where
#' the default behaviour is to produce a HTML fragment.
#' `htmltools::HTML()` is then used to evaluate the HTML code
#' within a RMarkdown chunk.
#'
#' @importFrom htmltools HTML
#' @importFrom markdown markdownToHTML
#'
#' @param text Character vector containing Markdown text
#'
#' @family Support
#'
#' @noRd
#'
md2html <- function(text){
html_chunk <- markdown::markdownToHTML(text = text,
fragment.only = TRUE)
htmltools::HTML(html_chunk)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/generate_report.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Generate HTML report based on existing RMarkdown documents
#'
#' @description
#' This is a support function that accepts parameters and creates a HTML
#' document based on an RMarkdown template. This is an alternative to
#' `generate_report()` which instead creates an RMarkdown document from scratch
#' using individual code chunks.
#'
#' @note
#' The implementation of this function was inspired by the 'DataExplorer'
#' package by boxuancui, with credits due to the original author.
#'
#' @param output_format output format in `rmarkdown::render()`. Default is
#' `rmarkdown::html_document(toc = TRUE, toc_depth = 6, theme = "cosmo")`.
#' @param output_file output file name in `rmarkdown::render()`. Default is
#' `"report.html"`.
#' @param output_dir output directory for report in `rmarkdown::render()`.
#' Default is user's current directory.
#' @param report_title report title. Default is `"Report"`.
#' @param rmd_dir string specifying the path to the directory containing the
#' RMarkdown template files.
#' @param \dots other arguments to be passed to `params`. For instance, pass
#' `hrvar` if the RMarkdown document requires a 'hrvar' parameter.
#' @export
generate_report2 <- function(output_format = rmarkdown::html_document(toc = TRUE, toc_depth = 6, theme = "cosmo"),
output_file = "report.html",
output_dir = getwd(),
report_title = "Report",
rmd_dir = system.file("rmd_template/minimal.rmd", package = "wpa"),
...) {
## Render report into html
suppressWarnings(
rmarkdown::render(
input = rmd_dir,
output_format = output_format,
output_file = output_file,
output_dir = output_dir,
intermediates_dir = output_dir,
params = list(set_title = report_title, ...)
))
## Open report
report_path <- path.expand(file.path(output_dir, output_file))
utils::browseURL(report_path)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/generate_report2.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
###################################################################
## Global Variables
## This file is added to minimize the false positives flagged during R CMD check.
## Example: afterhours_trend: no visible binding for global variable 'Date'
###################################################################
utils::globalVariables(
c(
"Date",
"Start",
"End",
"PersonId",
"group",
"Period",
"outcome",
".",
"After_hours_collaboration_hours",
"Employee_Count",
"bins",
"Metric",
"Hours",
"Collaboration_hours",
"Collaboration_hrs",
"Instant_message_hours",
"bucket_hours",
"Employees",
"Total",
"Value",
"Email_hours",
"External_network_size",
"Networking_outside_company",
"Ext_network_size",
"Ext_network_breadth",
"CH_ratio",
"Emails_sent",
"Email_ratio",
"WorkingEndTimeSetInOutlook",
"WorkingStartTimeSetInOutlook",
"WorkdayRange",
"WorkdayFlag",
"WorkdayFlag1",
"WorkdayFlag2",
"TimeInvestorOrg",
"CollaboratorOrg",
"metric_prop",
"output_list",
"n_unique",
"attribute",
"NA_per",
"no visible global function definition for head",
"mean_collab",
"holidayweek",
"ymin",
"ymax",
"z_score",
"Organization",
"flag_nkw",
"perc",
"tenure_years",
"odd_tenure",
"Internal_network_size",
"Networking_outside_organization",
"Int_network_size",
"Int_network_breadth",
"Workweek_span",
"Meeting_hours",
"Meetings",
"After_hours_meeting_hours",
"Low_quality_meeting_hours",
"Generated_workload_email_recipients",
"After_hours_email_hours",
"Total_focus_hours",
"variable",
"Multitasking_meeting_hours",
"Redundant_meeting_hours__organizational_",
"Conflicting_meeting_hours",
"Meeting_count",
"perc_after_hours_m",
"perc_low_quality",
"perc_Multitasking",
"perc_Redundant",
"perc_conflicting",
"Redundant_meeting_hours__lower_level_",
"HourType",
"extract_prop",
"extract_raw",
"RawHours",
"MeetingType",
"Attendee_meeting_hours",
"AttendeeMeetingHours",
"Prop",
"Duration",
"Attendees",
"Percent",
"value2",
"x",
"y",
"Meeting_hours_with_manager",
"coattendman_rate",
"bucket_coattendman_rate",
"Meeting_hours_with_manager_1_on_1",
"mgr1on1",
"coattendande",
"mgrRel",
"xmin",
"xmax",
"bucket_manager_1_on_1",
"Minutes_with_manager_1_on_1",
"Metrics",
"Values",
"Checks",
"Variables",
"UniqueValues",
"MissingValues",
"Examples",
"KPI",
"After",
"Before",
"delta",
"perc_diff",
"Mybins",
"Employee_perc",
"cluster",
"key",
"clusters",
"label",
"Signals",
"StartEnd",
"Before_start",
"Within_hours",
"After_end",
"Cases",
"subjectFlag",
"Subject",
"line",
"text",
"word",
"name",
"freq",
"pre_group",
"Utilization_hrs",
"UH_bin",
"UH_over_45",
"h_clust",
"dist_m",
"Signals_Total",
"Signals_sent",
"Personas",
"Employee_count",
"external_network_plot",
"total",
"value",
"prop",
"ODDS",
"..input_var2",
".N",
".SD",
"Freq",
"PersonCount",
"Shifts",
"Shoulders",
"per",
"sent",
"Fill",
"PersonWeekId",
"WeekCount",
"WeekPercentage",
"patternRank",
"Count",
"Day_Span",
"First_signal",
"Last_signal",
"MeetingHoursInLongOrLargeMeetings",
"Percentage",
"TenureYear",
"calculation",
"perc_nkw",
"value_rescaled",
"values",
"cleaned_data",
"zscore",
"StrongTieType",
"TieOrigin_PersonId",
"TieDestination_PersonId",
"Attribute 1",
"Attribute 2",
"Attribute 3",
"Community",
"Group",
"N",
"OrgGroup",
"PercentageExplained",
"V1",
"V2",
"Variable",
"c1",
"c2",
"c3",
"colour",
"feature_1",
"feature_1_value",
"feature_2",
"feature_2_value",
"feature_3",
"feature_3_value",
"from",
"percentage",
"print_str",
"pval",
"sum_na",
"to",
"top_group",
"AttendanceRate",
"DurationHours",
"Emails_sent_during_meetings",
"Emails_sent_per_attendee_hour",
"Invitees",
"IsRecurring",
"Mean_AttendanceRate",
"Mean_Attendees",
"Mean_DurationHours",
"Mean_Emails_sent_per_attendee_hour",
"Mean_Invitees",
"MeetingId",
"NRecurring",
"Sum_Attendee_meeting_hours",
"Total_meeting_cost",
"Attendee hours",
"DaySpan",
"Domain",
"Hour",
"PANEL",
"Time_in_self_organized_meetings",
"Type",
"labelpos",
"Cadence_of_1_on_1_meetings_with_manager",
"IV",
"Meetings_with_manager_1_on_1",
"org_size",
"var",
"var1",
"var2",
"where",
"WOE",
"ActivityLevel",
"Attributes",
"FirstValue",
"Flexibility",
"HRAttribute",
"identifier",
"PersonasNet",
"Unique values",
"Collaboration_hours_external",
".GRP",
"Id",
"betweenness",
"closeness",
"degree",
"eigenvector",
"node_size",
"pagerank"
)
)
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/globals.R
|
#' @title
#' Generate a vector of `n` contiguous colours, as a red-yellow-green palette.
#'
#' @description
#' Takes a numeric value `n` and returns a character vector of colour HEX codes
#' corresponding to the heat map palette.
#'
#' @param n the number of colors (>= 1) to be in the palette.
#' @param alpha an alpha-transparency level in the range of 0 to 1
#' (0 means transparent and 1 means opaque)
#' @param rev logical indicating whether the ordering of the colors should be
#' reversed.
#'
#' @examples
#' barplot(rep(10, 50), col = heat_colours(n = 50), border = NA)
#'
#' barplot(rep(10, 50), col = heat_colours(n = 50, alpha = 0.5, rev = TRUE),
#' border = NA)
#'
#' @family Support
#'
#' @return
#' A character vector containing the HEX codes and the same length as `n` is
#' returned.
#'
#' @export
heat_colours <- function (n, alpha, rev = FALSE) {
## Move from red to green
pre_h <- seq(from = 0, to = 0.3, length.out = n - 1)
h <- c(1, pre_h)
## Less bright
s <- rep(0.69, length(h))
## Increasingly low value (darker)
v <- seq(from = 1, to = 0.8, length.out = n)
cols <- grDevices::hsv(h = h, s = s, v = v, alpha = alpha)
if(rev){
rev(cols)
} else if(rev == FALSE) {
cols
}
}
#' @rdname heat_colours
#' @export
heat_colors <- heat_colours
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/heat_colours.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Employee count over time
#'
#' @description Returns a line chart showing the change in
#' employee count over time. Part of a data validation process to check
#' for unusual license growth / declines over time.
#'
#' @param data A Standard Person Query dataset in the form of a data frame.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: ggplot object. A line plot showing employee count over time.
#' - `"table"`: data frame containing a summary table.
#'
#' @import dplyr
#' @import ggplot2
#'
#' @examples
#' # Return plot
#' hr_trend(dv_data)
#'
#' # Return summary table
#' hr_trend(dv_data, return = "table")
#'
#' @family Visualization
#' @family Data Validation
#'
#' @export
hr_trend <- function(data, return = "plot"){
data$Date <- as.Date(data$Date, format = "%m/%d/%Y")
## Date range data frame
myPeriod <- extract_date_range(data)
plot_data <-
data %>%
group_by(Date) %>%
summarise(n = n_distinct(PersonId), .groups = "drop_last") %>%
ungroup()
if(return == "plot"){
plot_data %>%
ggplot(aes(x = Date, y = n)) +
geom_line(size = 1) +
labs(title = "Population over time",
subtitle = "Unique licensed population by week",
caption = paste("Data from week of", myPeriod$Start, "to week of", myPeriod$End)) +
ylab("Employee count") +
xlab("Date") +
scale_y_continuous(labels = round, limits = c(0,NA)) +
theme_wpa_basic()
} else if(return == "table"){
plot_data
} else {
stop("Please enter a valid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/hr_trend.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Create a count of distinct people in a specified HR variable
#'
#' @description
#' This function enables you to create a count of the distinct people
#' by the specified HR attribute.The default behaviour is to return a
#' bar chart as typically seen in 'Analysis Scope'.
#'
#' @param data A Standard Person Query dataset in the form of a data frame.
#' @param hrvar HR Variable by which to split metrics, defaults to
#' "Organization" but accepts any character vector, e.g. "LevelDesignation".
#' If a vector with more than one value is provided, the HR attributes are
#' automatically concatenated.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: 'ggplot' object containing a bar plot.
#' - `"table"`: data frame containing a count table.
#'
#' @import ggplot2
#' @import dplyr
#' @importFrom data.table ":=" "%like%" "%between%"
#'
#' @family Visualization
#' @family Data Validation
#'
#' @examples
#' # Return a bar plot
#' hrvar_count(sq_data, hrvar = "LevelDesignation")
#'
#' # Return a summary table
#' hrvar_count(sq_data, hrvar = "LevelDesignation", return = "table")
#'
#'@export
hrvar_count <- function(data,
hrvar = "Organization",
return = "plot"){
## Allow multiple HRvar inputs
if(length(hrvar) > 1){
hrvar_flat <- paste(hrvar, collapse = ", ")
summary_table <-
data %>%
select(PersonId, all_of(hrvar)) %>%
mutate(!!sym(hrvar_flat) := select(., hrvar) %>%
apply(1, paste, collapse = ", ")) %>%
group_by(!!sym(hrvar_flat)) %>%
summarise(n = n_distinct(PersonId)) %>%
arrange(desc(n))
# Single reference for single and multiple org attributes
hrvar_label <- hrvar_flat
} else {
summary_table <-
data %>%
select(PersonId, all_of(hrvar)) %>%
group_by(!!sym(hrvar)) %>%
summarise(n = n_distinct(PersonId)) %>%
arrange(desc(n))
# Single reference for single and multiple org attributes
hrvar_label <- hrvar
}
if(return == "table"){
data %>%
data.table::as.data.table() %>%
.[, .(n = n_distinct(PersonId)), by = hrvar] %>%
as_tibble() %>%
arrange(desc(n))
} else if(return == "plot"){
## This is re-run to enable multi-attribute grouping without concatenation
summary_table %>%
ggplot(aes(x = stats::reorder(!!sym(hrvar_label), -n),
y = n)) +
geom_col(fill = rgb2hex(0, 120, 212)) +
geom_text(aes(label = n),
vjust = -1,
fontface = "bold",
size = 4)+
theme_wpa_basic() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(title = paste("People by", camel_clean(hrvar_label))) +
scale_y_continuous(limits = c(0, max(summary_table$n) * 1.1)) +
xlab(camel_clean(hrvar_label)) +
ylab("Number of employees")
} else {
stop("Please enter a valid input for `return`.")
}
}
#' @rdname hrvar_count
#' @export
analysis_scope <- hrvar_count
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/hrvar_count.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Create count of distinct fields and percentage of employees with
#' missing values for all HR variables
#'
#' @description `r lifecycle::badge('experimental')`
#'
#' This function enables you to create a summary table to validate
#' organizational data. This table will provide a summary of the data found in
#' the Viva Insights _Data sources_ page. This function will return a summary
#' table with the count of distinct fields per HR attribute and the percentage
#' of employees with missing values for that attribute. See `hrvar_count()`
#' function for more detail on the specific HR attribute of interest.
#'
#' @param data A Standard Person Query dataset in the form of a data frame.
#' @param n_var number of HR variables to include in report as rows. Default is
#' set to 50 HR variables.
#' @param return String to specify what to return
#' @param threshold The max number of unique values allowed for any attribute.
#' Default is 100.
#' @param maxna The max percentage of NAs allowable for any column. Default is
#' 20.
#'
#' @import dplyr
#'
#' @family Data Validation
#'
#' @examples
#' # Return a summary table of all HR attributes
#' hrvar_count_all(sq_data, return = "table")
#'
#' @return
#' Returns an error message by default, where 'text' is passed in `return`.
#' - `'table'`: data frame. A summary table listing the number of distinct
#' fields and percentage of missing values for the specified number of HR
#' attributes will be returned.
#' - `'message'`: outputs a message indicating which values are
#' beyond the specified thresholds.
#'
#' @export
hrvar_count_all <- function(data,
n_var = 50,
return = "message",
threshold = 100,
maxna = 20
){
## Character vector of HR attributes
extracted_chr <- extract_hr(
data,
return = "names",
max_unique = threshold,
exclude_constants = FALSE
)
summary_table_n <-
data %>%
select(PersonId, extracted_chr) %>%
summarise_at(vars(extracted_chr), ~n_distinct(.,na.rm = TRUE)) # Excludes NAs from unique count
## Note: WPA here is used for a matching separator
results <-
data %>%
select(PersonId, extracted_chr) %>%
summarise_at(vars(extracted_chr),
list(`WPAn_unique` = ~n_distinct(., na.rm = TRUE), # Excludes NAs from unique count
`WPAper_na` = ~(sum(is.na(.))/ nrow(data) * 100),
`WPAsum_na` = ~sum(is.na(.)) # Number of missing values
)) %>% # % of missing values
tidyr::gather(attribute, values) %>%
tidyr::separate(col = attribute, into = c("attribute", "calculation"), sep = "_WPA") %>%
tidyr::spread(calculation, values)
## Single print message
if(sum(results$n_unique >= threshold)==0){
printMessage <- paste("No attributes have greater than", threshold, "unique values.")
}
if(sum(results$per_na >= maxna)==0){
newMessage <- paste("No attributes have more than", maxna, "percent NA values.")
printMessage <- paste(printMessage, newMessage, collapse = "\n")
}
for (i in 1:nrow(results)) {
if(results$n_unique[i] >= threshold){
newMessage <- paste0("The attribute '",results$attribute[i],"' has a large amount of unique values. Please check.")
printMessage <- paste(printMessage, newMessage, collapse = "\n")
}
if(results$per_na[i]>=maxna){
newMessage <- paste0("The attribute '",results$attribute[i],"' has a large amount of NA values. Please check.")
printMessage <- paste(printMessage, newMessage, collapse = "\n")
}
}
if(return == "table"){
results <-
results %>%
select(Attributes = "attribute",
`Unique values` = "n_unique",
`Total missing values` = "sum_na",
`% missing values` = "per_na")
return(utils::head(results, n_var))
} else if(return == "text"){
printMessage
} else if(return == "message"){
message(printMessage)
} else {
stop("Error: please check inputs for `return`")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/hrvar_count_all.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Track count of distinct people over time in a specified HR variable
#'
#' @description
#' This function provides a week by week view of the count of the distinct
#' people by the specified HR attribute.The default behaviour is to return a
#' week by week heatmap bar plot.
#'
#' @param data A Standard Person Query dataset in the form of a data frame.
#' @param hrvar HR Variable by which to split metrics, defaults to
#' "Organization" but accepts any character vector, e.g. "LevelDesignation".
#' If a vector with more than one value is provided, the HR attributes are
#' automatically concatenated.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: 'ggplot' object containing a bar plot.
#' - `"table"`: data frame containing a count table.
#'
#' @import ggplot2
#' @import dplyr
#' @importFrom data.table ":=" "%like%" "%between%"
#'
#' @family Visualization
#' @family Data Validation
#'
#' @examples
#' # Return a bar plot
#' hrvar_trend(sq_data, hrvar = "LevelDesignation")
#'
#' # Return a summary table
#' hrvar_trend(sq_data, hrvar = "LevelDesignation", return = "table")
#'
#'@export
hrvar_trend <- function(data,
hrvar = "Organization",
return = "plot"){
## Allow multiple HRvar inputs
if(length(hrvar) > 1){
hrvar_flat <- paste(hrvar, collapse = ", ")
summary_table <-
data %>%
select(PersonId, Date, all_of(hrvar)) %>%
mutate(!!sym(hrvar_flat) := select(., hrvar) %>%
apply(1, paste, collapse = ", ")) %>%
group_by(Date, !!sym(hrvar_flat)) %>%
summarise(n = n_distinct(PersonId)) %>%
arrange(desc(n))
# Single reference for single and multiple org attributes
hrvar_label <- hrvar_flat
} else {
summary_table <-
data %>%
select(PersonId, Date, all_of(hrvar)) %>%
group_by(Date, !!sym(hrvar)) %>%
summarise(n = n_distinct(PersonId)) %>%
arrange(desc(n))
# Single reference for single and multiple org attributes
hrvar_label <- hrvar
}
if(return == "table"){
summary_table %>%
mutate(PersonId = "") %>%
create_trend(metric = "n",
hrvar = hrvar,
mingroup = 0,
return = "table")
} else if(return == "plot"){
## This is re-run to enable multi-attribute grouping without concatenation
summary_table %>%
mutate(PersonId="") %>%
create_trend(metric = "n",
hrvar = hrvar,
mingroup = 0,
return = "plot",
legend_title = "Number of employees") +
labs(title = "Employees over time",
subtitle = paste0("Dynamics by ", tolower(camel_clean(hrvar))))
} else {
stop("Please enter a valid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/hrvar_trend.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Identify employees who have churned from the dataset
#'
#' @description
#' This function identifies and counts the number of employees who have churned
#' from the dataset by measuring whether an employee who is present in the first
#' `n` (n1) weeks of the data is present in the last `n` (n2) weeks of the data.
#'
#' @details
#' An additional use case of this function is the ability to identify
#' "new-joiners" by using the argument `flip`.
#'
#' @param data A Person Query as a data frame. Must contain a `PersonId`.
#' @param n1 A numeric value specifying the number of weeks at the beginning of
#' the period that defines the measured employee set. Defaults to 6.
#' @param n2 A numeric value specifying the number of weeks at the end of the
#' period to calculate whether employees have churned from the data. Defaults
#' to 6.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"message"` (default)
#' - `"text"`
#' - `"data"`
#'
#' See `Value` for more information.
#'
#' @param flip Logical, defaults to FALSE. This determines whether to reverse
#' the logic of identifying the non-overlapping set. If set to `TRUE`, this
#' effectively identifies new-joiners, or those who were not present in the
#' first n weeks of the data but were present in the final n weeks.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"message"`: Message on console. A diagnostic message.
#' - `"text"`: String. A diagnostic message.
#' - `"data"`: Character vector containing the the `PersonId` of
#' employees who have been identified as churned.
#'
#' @details
#' If an employee is present in the first `n` weeks of the data but not present
#' in the last `n` weeks of the data, the function considers the employee as
#' churned. As the measurement period is defined by the number of weeks from the
#' start and the end of the passed data frame, you may consider filtering the
#' dates accordingly before running this function.
#'
#' Another assumption that is in place is that any employee whose `PersonId` is
#' not available in the data has churned. Note that there may be other reasons
#' why an employee's `PersonId` may not be present, e.g. maternity/paternity
#' leave, Viva Insights license has been removed, shift to a
#' low-collaboration role (to the extent that he/she becomes inactive).
#'
#' @family Data Validation
#'
#' @examples
#' sq_data %>% identify_churn(n1 = 3, n2 = 3, return = "message")
#'
#' @export
identify_churn <- function(data,
n1 = 6,
n2 = 6,
return = "message",
flip = FALSE){
data$Date <- as.Date(data$Date, format = "%m/%d/%Y") # Ensure correct format
unique_dates <- unique(data$Date) # Vector of unique dates
nlen <- length(unique_dates) # Total number of unique dates
# First and last n weeks
firstnweeks <- sort(unique_dates)[1:n1]
lastnweeks <- sort(unique_dates, decreasing = TRUE)[1:n2]
## People in the first week
first_peeps <-
data %>%
dplyr::filter(Date %in% firstnweeks) %>%
dplyr::pull(PersonId) %>%
unique()
## People in the last week
final_peeps <-
data %>%
dplyr::filter(Date %in% lastnweeks) %>%
dplyr::pull(PersonId) %>%
unique()
if(flip == FALSE){
## In first, not in last
churner_id <- setdiff(first_peeps, final_peeps)
## Message
printMessage <-
paste0("Churn:\nThere are ", length(churner_id),
" employees from ", min(firstnweeks), " to ",
max(firstnweeks), " (", n1, " weeks)",
" who are no longer present in ",
min(lastnweeks), " to ", max(lastnweeks),
" (", n2, " weeks).")
} else if(flip == TRUE){
## In last, not in first
## new joiners
churner_id <- dplyr::setdiff(final_peeps, first_peeps)
## Message
printMessage <-
paste0("New joiners:\nThere are ", length(churner_id),
" employees from ", min(lastnweeks), " to ",
max(lastnweeks), " (", n2, " weeks)",
" who were not present in ",
min(firstnweeks), " to ", max(firstnweeks),
" (", n1, " weeks).")
} else {
stop("Invalid argument for `flip`")
}
if(return == "message"){
message(printMessage)
} else if(return == "text"){
printMessage
} else if(return == "data"){
churner_id
} else {
stop("Invalid `return`")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/identify_churn.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Identify date frequency based on a series of dates
#'
#' @description
#' `r lifecycle::badge('experimental')`
#'
#' Takes a vector of dates and identify whether the frequency is 'daily',
#' 'weekly', or 'monthly'. The primary use case for this function is to provide
#' an accurate description of the query type used and for raising errors should
#' a wrong date grouping be used in the data input.
#'
#' @param x Vector containing a series of dates.
#'
#' @details
#' Date frequency detection works as follows:
#' - If at least three days of the week are present (e.g., Monday, Wednesday,
#' Thursday) in the series, then the series is classified as 'daily'
#' - If the total number of months in the series is equal to the length, then
#' the series is classified as 'monthly'
#' - If the total number of sundays in the series is equal to the length of
#' the series, then the series is classified as 'weekly
#'
#' @section Limitations:
#' One of the assumptions made behind the classification is that weeks are
#' denoted with Sundays, hence the count of sundays to measure the number of
#' weeks. In this case, weeks where a Sunday is missing would result in an
#' 'unable to classify' error.
#'
#' Another assumption made is that dates are evenly distributed, i.e. that the
#' gap between dates are equal. If dates are unevenly distributed, e.g. only two
#' days of the week are available for a given week, then the algorithm will fail
#' to identify the frequency as 'daily'.
#'
#' @return
#' String describing the detected date frequency, i.e.:
#' - 'daily'
#' - 'weekly'
#' - 'monthly'
#'
#' @examples
#' start_date <- as.Date("2022/06/26")
#' end_date <- as.Date("2022/11/27")
#'
#' # Daily
#' day_seq <-
#' seq.Date(
#' from = start_date,
#' to = end_date,
#' by = "day"
#' )
#'
#' identify_datefreq(day_seq)
#'
#' # Weekly
#' week_seq <-
#' seq.Date(
#' from = start_date,
#' to = end_date,
#' by = "week"
#' )
#'
#' identify_datefreq(week_seq)
#'
#' # Monthly
#' month_seq <-
#' seq.Date(
#' from = start_date,
#' to = end_date,
#' by = "month"
#' )
#' identify_datefreq(month_seq)
#'
#' @export
identify_datefreq <- function(x){
# Data frame for checking
date_df <- data.frame(
weekdays = names(table(weekdays(x))),
n = as.numeric(table(weekdays(x)))
)
dweekchr <- c(
"Sunday",
"Saturday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday"
)
# At least 3 days of the week must be present
check_wdays <- ifelse(
sum(dweekchr %in% date_df$weekdays) >= 3, TRUE, FALSE)
# Check number of Sundays - should equal number of weeks if weekly
check_nsun <- sum(date_df$n[date_df$weekdays == "Sunday"])
ifelse(
length(months(x)) == length(x),
"monthly",
ifelse(
check_nsun == length(x),
"weekly",
ifelse(
check_wdays,
"daily",
"Unable to identify date frequency."
)
)
)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/identify_datefreq.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Identify Holiday Weeks based on outliers
#'
#' @description
#' This function scans a standard query output for weeks where collaboration
#' hours is far outside the mean. Returns a list of weeks that appear to be
#' holiday weeks and optionally an edited dataframe with outliers removed. By
#' default, missing values are excluded.
#'
#' As best practice, run this function prior to any analysis to remove atypical
#' collaboration weeks from your dataset.
#'
#' @template ch
#'
#' @param data A Standard Person Query dataset in the form of a data frame.
#' @param sd The standard deviation below the mean for collaboration hours that
#' should define an outlier week. Enter a positive number. Default is 1
#' standard deviation.
#'
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"message"` (default)
#' - `"data"`
#' - `"data_cleaned"`
#' - `"data_dirty"`
#' - `"plot"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"message"`: message on console. a message is printed identifying holiday
#' weeks.
#' - `"data"`: data frame. A dataset with outlier weeks flagged in a new
#' column is returned as a dataframe.
#' - `"data_cleaned"`: data frame. A dataset with outlier weeks removed is
#' returned.
#' - `"data_dirty"`: data frame. A dataset with only outlier weeks is
#' returned.
#' - `"plot"`: ggplot object. A line plot of Collaboration Hours with holiday
#' weeks highlighted.
#'
#'
#' @import dplyr
#' @import ggplot2
#' @importFrom methods is
#'
#' @family Data Validation
#'
#' @examples
#' # Return a message by default
#' identify_holidayweeks(sq_data)
#'
#' # Return plot
#' identify_holidayweeks(sq_data, return = "plot")
#'
#' @export
identify_holidayweeks <- function(data, sd = 1, return = "message"){
## Ensure date is formatted
if(all(is_date_format(data$Date))){
data$Date <- as.Date(data$Date, format = "%m/%d/%Y")
} else if(is(data$Date, "Date")){
# Do nothing
} else {
stop("`Date` appears not to be properly formatted.\n
It needs to be in the format MM/DD/YYYY.\n
Also check for missing values or stray values with inconsistent formats.")
}
Calc <-
data %>%
group_by(Date) %>%
summarize(mean_collab = mean(Collaboration_hours, na.rm = TRUE),.groups = 'drop') %>%
mutate(z_score = (mean_collab - mean(mean_collab, na.rm = TRUE))/ sd(mean_collab, na.rm = TRUE))
Outliers = (Calc$Date[Calc$z_score < -sd])
mean_collab_hrs <- mean(Calc$mean_collab, na.rm = TRUE)
Message <- paste0("The weeks where collaboration was ",
sd,
" standard deviations below the mean (",
round(mean_collab_hrs, 1),
") are: \n",
paste(wrap(Outliers, wrapper = "`"),collapse = ", "))
myTable_plot <-
data %>%
mutate(holidayweek = (Date %in% Outliers)) %>%
select("Date", "holidayweek", "Collaboration_hours") %>%
group_by(Date) %>%
summarise(Collaboration_hours=mean(Collaboration_hours), holidayweek=first(holidayweek)) %>%
mutate(Date=as.Date(Date, format = "%m/%d/%Y"))
myTable_plot_shade <-
myTable_plot %>%
filter(holidayweek == TRUE) %>%
mutate(min = Date - 3 , max = Date + 3 , ymin = -Inf, ymax = +Inf)
plot <-
myTable_plot %>%
ggplot(aes(x = Date, y = Collaboration_hours, group = 1)) +
geom_line(colour = "grey40") +
theme_wpa_basic() +
geom_rect(data = myTable_plot_shade,
aes(xmin = min,
xmax = max,
ymin = ymin,
ymax = ymax),
color = "transparent",
fill = "steelblue",
alpha = 0.3) +
labs(title = "Holiday Weeks",
subtitle = "Showing average collaboration hours over time")+
ylab("Collaboration Hours") +
xlab("Date") +
ylim(0, NA) # Set origin to zero
if(return == "text"){
return(Message)
} else if(return == "message"){
message(Message)
} else if(return %in% c("data_clean", "data_cleaned")){
return(data %>% filter(!(Date %in% Outliers)) %>% data.frame())
} else if(return == "data_dirty"){
return(data %>% filter((Date %in% Outliers)) %>% data.frame())
} else if(return == "data"){
return(data %>% mutate(holidayweek = (Date %in% Outliers)) %>% data.frame())
} else if(return == "plot"){
return(plot)
} else {
stop("Invalid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/identify_holidayweeks.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Identify Inactive Weeks
#'
#' @description
#' This function scans a standard query output for weeks where collaboration
#' hours is far outside the mean for any individual person in the dataset.
#' Returns a list of weeks that appear to be inactive weeks and optionally an
#' edited dataframe with outliers removed.
#'
#' As best practice, run this function prior to any analysis to remove atypical
#' collaboration weeks from your dataset.
#'
#' @param data A Standard Person Query dataset in the form of a data frame.
#' @param sd The standard deviation below the mean for collaboration hours that
#' should define an outlier week. Enter a positive number. Default is 1
#' standard deviation.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"text"`
#' - `"data_cleaned"`
#' - `"data_dirty"`
#'
#' See `Value` for more information.
#'
#' @import dplyr
#'
#' @family Data Validation
#'
#' @return
#' Returns an error message by default, where `'text'` is returned. When
#' `'data_cleaned'` is passed, a dataset with outlier weeks removed is returned
#' as a dataframe. When `'data_dirty'` is passed, a dataset with outlier weeks
#' is returned as a dataframe.
#'
#' @export
identify_inactiveweeks <- function(data, sd = 2, return = "text"){
init_data <-
data %>%
group_by(PersonId) %>%
mutate(z_score = (Collaboration_hours - mean(Collaboration_hours))/sd(Collaboration_hours))
Calc <-
init_data %>%
filter(z_score <= -sd) %>%
select(PersonId, Date, z_score) %>%
data.frame()
pop_mean <-
data %>%
dplyr::mutate(Total = "Total") %>%
create_bar(metric = "Collaboration_hours",
hrvar = "Total",
return = "table") %>%
dplyr::pull(Collaboration_hours) %>%
round(digits = 1)
Message <- paste0("There are ", nrow(Calc), " rows of data with weekly collaboration hours more than ",
sd," standard deviations below the mean (", pop_mean, ").")
if(return == "text"){
return(Message)
} else if(return == "data_dirty"){
init_data %>%
filter(z_score <= -sd) %>%
select(-z_score) %>%
data.frame()
} else if(return == "data_cleaned"){
init_data %>%
filter(z_score > -sd) %>%
select(-z_score) %>%
data.frame()
} else if(return == "data"){
init_data %>%
mutate(inactiveweek = (z_score<= -sd)) %>%
select(-z_score) %>%
data.frame()
} else {
stop("Error: please check inputs for `return`")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/identify_inactiveweeks.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Identify Non-Knowledge workers in a Person Query using Collaboration
#' Hours
#'
#' @description
#' This function scans a standard query output to identify employees with
#' consistently low collaboration signals. Returns the % of non-knowledge
#' workers identified by Organization, and optionally an edited data frame with
#' non-knowledge workers removed, or the full data frame with the kw/nkw flag
#' added.
#'
#' @param data A Standard Person Query dataset in the form of a data frame.
#' @param collab_threshold Positive numeric value representing the collaboration
#' hours threshold that should be exceeded as an average for the entire
#' analysis period for the employee to be categorized as a knowledge worker
#' ("kw"). Default is set to 5 collaboration hours. Any versions after v1.4.3,
#' this uses a "greater than or equal to" logic (`>=`), in which case persons
#' with exactly 5 collaboration hours will pass.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"text"`
#' - `"data_with_flag"`
#' - `"data_clean"`
#' - `"data_summary"`
#'
#' See `Value` for more information.
#'
#' @import dplyr
#'
#' @family Data Validation
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"text"`: string. Returns a diagnostic message.
#' - `"data_with_flag"`: data frame. Original input data with an additional
#' column containing the `kw`/`nkw` flag.
#' - `"data_clean"`: data frame. Data frame with non-knowledge workers
#' excluded.
#' - `"data_summary"`: data frame. A summary table by organization listing
#' the number and % of non-knowledge workers.
#'
#' @export
identify_nkw <- function(data, collab_threshold = 5, return = "data_summary"){
summary_byPersonId <-
data %>%
group_by(PersonId, Organization) %>%
summarize(mean_collab = mean(Collaboration_hours), .groups = "drop")%>%
mutate(flag_nkw = case_when(mean_collab >= collab_threshold ~ "kw",
TRUE ~ "nkw"))
data_with_flag <-
left_join(data,
summary_byPersonId %>%
dplyr::select(PersonId,flag_nkw),
by = 'PersonId')
summary_byOrganization <-
summary_byPersonId %>%
group_by(Organization, flag_nkw)%>%
summarise(total = n(), .groups = "drop")%>%
group_by(Organization)%>%
mutate(perc = total/sum(total))%>% #need to format to %
filter(flag_nkw == "nkw")%>%
rename(n_nkw = total, perc_nkw = perc)%>%
select(-flag_nkw) %>%
ungroup()
## Number of NKW identified
n_nkw <- sum(summary_byPersonId$flag_nkw == "nkw")
if(n_nkw == 0){
flagMessage <- paste0("[Pass] There are no non-knowledge workers identified",
" (average collaboration hours below ",
collab_threshold,
" hours).")
} else {
flagMessage <-
paste0("[Warning] Out of a population of ", n_distinct(data$PersonId),
", there are ", n_nkw,
" employees who may be non-knowledge workers (average collaboration hours below ",
collab_threshold, " hours).")
}
if(return == "data_with_flag"){
return(data_with_flag)
} else if(return %in% c("data_clean", "data_cleaned")){
data_with_flag %>%
filter(flag_nkw == "kw")
} else if(return == "text"){
flagMessage
} else if(return =="data_summary"){
summary_byOrganization %>%
mutate(perc_nkw = scales::percent(perc_nkw, accuracy = 1)) %>%
rename(`Non-knowledge workers (count)` = "n_nkw",
`Non-knowledge workers (%)` = "perc_nkw")
} else {
stop("Error: please check inputs for `return`")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/identify_nkw.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Identify metric outliers over a date interval
#'
#' @description This function takes in a selected metric and uses
#' z-score (number of standard deviations) to identify outliers
#' across time. There are applications in this for identifying
#' weeks with abnormally low collaboration activity, e.g. holidays.
#' Time as a grouping variable can be overridden with the `group_var`
#' argument.
#'
#' @param data A Standard Person Query dataset in the form of a data frame.
#' @param group_var A string with the name of the grouping variable.
#' Defaults to `Date`.
#' @param metric Character string containing the name of the metric,
#' e.g. "Collaboration_hours"
#'
#' @import dplyr
#'
#' @examples
#' identify_outlier(sq_data, metric = "Collaboration_hours")
#'
#' @return
#' Returns a data frame with `Date` (if grouping variable is not set),
#' the metric, and the corresponding z-score.
#'
#' @family Data Validation
#'
#' @export
identify_outlier <- function(data,
group_var = "Date",
metric = "Collaboration_hours"){
## Check inputs
required_variables <- c(group_var,
"PersonId",
metric)
## Error message if variables are not present
## Nothing happens if all present
data %>%
check_inputs(requirements = required_variables)
main_table <-
data %>%
group_by(!!sym(group_var)) %>%
summarise_at(vars(!!sym(metric)), ~mean(.)) %>%
mutate(zscore = (!!sym(metric) - mean(!!sym(metric)))/sd(!!sym(metric)))
return(main_table)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/identify_outlier.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Identify groups under privacy threshold
#'
#' @description
#' This function scans a standard query output for groups with of employees
#' under the privacy threshold. The method consists in reviewing each individual
#' HR attribute, and count the distinct people within each group.
#'
#' @param data A Standard Person Query dataset in the form of a data frame.
#' @param hrvar A list of HR Variables to consider in the scan.
#' Defaults to all HR attributes identified.
#' @param mingroup Numeric value setting the privacy threshold / minimum group
#' size. Defaults to 5.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"table"`
#' - `"text"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"table"`: data frame. A summary table of groups that fall below the
#' privacy threshold.
#' - `"text"`: string. A diagnostic message.
#'
#' @examples
#' # Return a summary table
#' dv_data %>% identify_privacythreshold(return = "table")
#'
#' # Return a diagnostic message
#' dv_data %>% identify_privacythreshold(return = "text")
#'
#' @import dplyr
#' @import ggplot2
#' @import reshape2
#' @import scales
#' @importFrom stats reorder
#'
#' @family Data Validation
#'
#' @return
#' Returns a ggplot object by default, where 'plot' is passed in `return`.
#' When 'table' is passed, a summary table is returned as a data frame.
#'
#' @export
identify_privacythreshold <- function(data,
hrvar = extract_hr(data),
mingroup = 5,
return = "table"){
results <-
data %>% hrvar_count(
hrvar = hrvar[1],
return = "table")
results$hrvar <- ""
results <- results[0,]
for (p in hrvar) {
table1 <-
data %>%
hrvar_count(hrvar = p,
return = "table")
table1$hrvar <- p
colnames(table1)[1] <- "group"
results <- rbind(results,table1)
}
output <- results %>% arrange(n) %>% select(hrvar, everything())
groups_under <- results %>% filter(n<mingroup) %>% nrow()
MinGroupFlagMessage_Warning <- paste0("[Warning] There are ", groups_under, " groups under the minimum group size privacy threshold of ", mingroup, ".")
MinGroupFlagMessage_Low <- paste0("[Pass] There is only ", groups_under, " group under the minimum group size privacy threshold of ", mingroup, ".")
MinGroupFlagMessage_Zero <- paste0("[Pass] There are no groups under the minimum group size privacy threshold of ", mingroup, ".")
if(groups_under > 1){
MinGroupFlagMessage <- MinGroupFlagMessage_Warning
} else if(groups_under == 1 ){
MinGroupFlagMessage <- MinGroupFlagMessage_Low
} else if(groups_under ==0){
MinGroupFlagMessage <- MinGroupFlagMessage_Zero
}
if(return == "table"){
return(output)
} else if(return == "message"){
message(MinGroupFlagMessage)
} else if(return == "text"){
MinGroupFlagMessage
} else {
stop("Invalid `return` argument.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/identify_privacythreshold.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Identify the query type of the passed data frame
#'
#' @description
#' Pass an advanced insights query dataset and return the identified query type
#' as a string. This function uses variable name string matching to 'guess' the
#' query type of the data frame.
#'
#' @param data An advanced insights query dataset in the form of a data frame.
#' If the data is not identified as a valid dataset, the function will return
#' an error.
#' @param threshold Debugging use only. Increase to raise the 'strictness' of
#' the guessing algorithm. Defaults to 2.
#'
#' @family Data Validation
#'
#' @return String. A diagnostic message is returned.
#'
#' @examples
#' identify_query(sq_data) # Standard query
#' identify_query(mt_data) # Meeting query
#' identify_query(em_data) # Hourly collaboration query
#' \dontrun{
#' identify_query(iris) # Will return an error
#' identify_query(mtcars) # Will return an error
#' }
#' @export
identify_query <- function(data, threshold = 2){
## variables to check for in each query type
spq_var <- c("PersonId", "Collaboration_hours", "Instant_Message_hours") # Standard Person query
caq_var <- c("PersonId", "Collaboration_hrs", "Instant_message_hours") # Ways of Working Assessment query
smq_var <- c("MeetingId", "Date", "Attendees") # Standard Meeting Query
shc_var <- c("PersonId", "Emails_sent_00_01", "IMs_sent_23_24") # Standard Hourly Collaboration
## see if there are columns which do not exist
spq_check <- check_inputs(input = data, requirements = spq_var, return = "names")
caq_check <- check_inputs(input = data, requirements = caq_var, return = "names")
smq_check <- check_inputs(input = data, requirements = smq_var, return = "names")
shc_check <- check_inputs(input = data, requirements = shc_var, return = "names")
## length of checks
spq_check_n <- length(spq_check)
caq_check_n <- length(caq_check)
smq_check_n <- length(smq_check)
shc_check_n <- length(shc_check)
total_check_vec <- c(spq_check_n, caq_check_n, smq_check_n, shc_check_n)
## should never be zero
total_check_n <- sum(total_check_vec, na.rm = TRUE)
## Labels
qlabels <- c("Person Query",
"Ways of Working Assessment Query",
"Meeting Query",
"Hourly Collaboration Query")
## Minimum number of non-matches
min_nm <- min(total_check_vec)
## Final guess
f_guess <- qlabels[which.min(total_check_vec)]
if(total_check_n == 0){
stop("Error: please check if query data is properly formatted query data.")
} else if(min_nm > threshold){
stop("Column mismatches: please check if query data is properly formatted query data.")
} else {
f_guess
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/identify_query.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title
#' Identify shifts based on outlook time settings for work day start and end
#' time
#'
#' @description
#' This function uses outlook calendar settings for start and end time of work
#' day to identify work shifts. The relevant variables are
#' `WorkingStartTimeSetInOutlook` and `WorkingEndTimeSetInOutlook`.
#'
#'
#' @param data A data frame containing data from the Hourly Collaboration query.
#'
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#' - `"data"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: ggplot object. A bar plot for the weekly count of shifts.
#' - `"table"`: data frame. A summary table for the count of shifts.
#' - `"data`: data frame. Input data appended with the `Shifts` columns.
#'
#' @importFrom data.table ":=" "%like%" "%between%"
#'
#' @family Data Validation
#' @family Working Patterns
#'
#' @examples
#' # Return plot
#' dv_data %>% identify_shifts()
#'
#' # Return summary table
#' dv_data %>% identify_shifts(return = "table")
#'
#' @export
identify_shifts <- function(data, return = "plot"){
clean_times <- function(x){
out <- gsub(pattern = ":00", replacement = "", x = x)
as.numeric(out)
}
data <- data.table::as.data.table(data)
# data <- data.table::copy(data)
# Make sure data.table knows we know we're using it
.datatable.aware = TRUE
data[, Shifts := paste(WorkingStartTimeSetInOutlook, WorkingEndTimeSetInOutlook, sep = "-")]
# outputTable <- data[, .(count = .N), by = Shifts]
outputTable <- data[, list(WeekCount = .N,
PersonCount = dplyr::n_distinct(PersonId)), by = Shifts]
outputTable <- data.table::setorder(outputTable, -PersonCount)
if(return == "table"){
dplyr::as_tibble(outputTable)
} else if(return == "plot"){
outputTable %>%
utils::head(10) %>%
create_bar_asis(group_var = "Shifts",
bar_var = "WeekCount",
title = "Most frequent outlook shifts",
subtitle = "Showing top 10 only",
caption = extract_date_range(data, return = "text"),
ylab = "Shifts",
xlab = "Frequency")
} else if(return == "data"){
output_data <- data
dplyr::as_tibble(output_data)
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/identify_shifts.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Identify shifts based on binary activity
#'
#' @description
#' This function uses the Hourly Collaboration query and computes binary
#' activity to identify the 'behavioural' work shift. This is a distinct method
#' to `identify_shifts()`, which instead uses outlook calendar settings for
#' start and end time of work day to identify work shifts. The two methods can
#' be compared to gauge the accuracy of existing Outlook settings.
#'
#' @param data A data frame containing data from the Hourly Collaboration query.
#'
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#' - `"data"`
#'
#' See `Value` for more information.
#'
#' @param percent Logical value to determine whether to show labels as
#' percentage signs. Defaults to `FALSE`.
#'
#' @param n Numeric value specifying number of shifts to show. Defaults to 10.
#' This parameter is only used when `return` is set to `"plot"`,
#'
#' @inheritParams workpatterns_classify_bw
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: ggplot object. A bar plot for the weekly count of shifts.
#' - `"table"`: data frame. A summary table for the count of shifts.
#' - `"data`: data frame. Input data appended with the following columns:
#' - `Start`
#' - `End`
#' - `DaySpan`
#' - `Shifts`
#'
#' @importFrom data.table ":=" "%like%" "%between%"
#'
#' @family Data Validation
#' @family Working Patterns
#'
#' @examples
#' # Return plot
#' em_data %>% identify_shifts_wp()
#'
#' # Return plot - showing percentages
#' em_data %>% identify_shifts_wp(percent = TRUE)
#'
#' # Return table
#' em_data %>% identify_shifts_wp(return = "table")
#'
#' @export
identify_shifts_wp <- function(data,
signals = c("email",
"IM"),
active_threshold = 1,
start_hour = 9,
end_hour = 17,
percent = FALSE,
n = 10,
return = "plot"){
## Remove case-sensitivity for signals
signals <- tolower(signals)
## Text replacement only for allowed values
if(any(signals %in% c("email", "im", "unscheduled_calls", "meetings"))){
signal_set <- gsub(pattern = "email", replacement = "Emails_sent", x = signals) # case-sensitive
signal_set <- gsub(pattern = "im", replacement = "IMs_sent", x = signal_set)
signal_set <- gsub(pattern = "unscheduled_calls", replacement = "Unscheduled_calls", x = signal_set)
signal_set <- gsub(pattern = "meetings", replacement = "Meetings", x = signal_set)
total_signal_set <- paste0(signal_set, "_total")
search_set <- paste(paste0("^", signal_set, "_"), collapse = "|")
} else {
stop("Invalid input for `signals`.")
}
## Create 24 summed `Signals_sent` columns
signal_cols <-
purrr::map(0:23,
~combine_signals(data,
hr = .,
signals = signal_set)) %>%
dplyr::bind_cols()
## Use names for matching
input_var <- names(signal_cols)
## Signals sent by Person and date
signals_df <-
data %>%
.[, c("PersonId", "Date")] %>%
cbind(signal_cols)
## Signal label
sig_label <- "Signals_sent"
## Create binary variable 0 or 1
num_cols <- names(which(sapply(signals_df, is.numeric))) # Get numeric columns
signals_df <-
signals_df %>%
data.table::as.data.table() %>%
# Minimum number of signals to qualify as working
.[, (num_cols) := lapply(.SD, function(x) ifelse(x > active_threshold, 1, 0)), .SDcols = num_cols]
## Computed data frame with the following columns
## - Start
## - End
## - DaySpan
## - Shifts
out_data <-
signals_df %>%
as.data.frame() %>%
pivot_longer(cols = input_var, names_to = "Signals") %>%
mutate(Hour = gsub(pattern = "Signals_sent_", replacement = "", x = Signals)) %>%
mutate(Hour = gsub(pattern = "_.+", replacement = "", x = Hour) %>%
as.numeric()) %>%
select(PersonId, Date, Hour, value) %>%
filter(value == 1) %>%
arrange(Hour) %>%
group_by(PersonId, Date) %>%
summarise(Start = first(Hour),
End = last(Hour)) %>%
ungroup() %>%
mutate(Shifts = paste0(Start, ":00-", End, ":00")) %>%
mutate(DaySpan = End - Start)
if(return == "data"){
out_data
} else if(return == "table"){
out_data %>%
group_by(Shifts, DaySpan) %>%
summarise(WeekCount = n(),
PersonCount = n_distinct(PersonId)) %>%
arrange(desc(WeekCount)) %>%
ungroup() %>%
mutate(`Week%` = WeekCount / sum(WeekCount, na.rm = TRUE),
`Person%` = PersonCount / sum(PersonCount, na.rm = TRUE))
} else if(return == "plot"){
out_data %>%
group_by(Shifts) %>%
summarise(WeekCount = n()) %>%
{ if(percent == TRUE){
mutate(., WeekCount = WeekCount / sum(WeekCount, na.rm = TRUE))
} else {
.
}
} %>%
arrange(desc(WeekCount)) %>%
utils::head(n) %>%
create_bar_asis(group_var = "Shifts",
bar_var = "WeekCount",
title = "Most frequent shifts",
subtitle = paste("Showing top", n),
caption = extract_date_range(data, return = "text"),
ylab = "Shifts",
xlab = "Frequency",
percent = percent)
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/identify_shifts_wp.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Tenure calculation based on different input dates, returns data
#' summary table or histogram
#'
#' @description
#' This function calculates employee tenure based on different input dates.
#' `identify_tenure` uses the latest Date available if user selects "Date",
#' but also have flexibility to select a specific date, e.g. "1/1/2020".
#'
#' @family Data Validation
#'
#' @param data A Standard Person Query dataset in the form of a data frame.
#' @param end_date A string specifying the name of the date variable
#' representing the latest date. Defaults to "Date".
#' @param beg_date A string specifying the name of the date variable
#' representing the hire date. Defaults to "HireDate".
#' @param maxten A numeric value representing the maximum tenure.
#' If the tenure exceeds this threshold, it would be accounted for in the flag message.
#'
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"message"`
#' - `"text"`
#' - `"plot"`
#' - `"data_cleaned"`
#' - `"data_dirty"`
#' - `"data"`
#'
#' See `Value` for more information.
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"message"`: message on console with a diagnostic message.
#' - `"text"`: string containing a diagnostic message.
#' - `"plot"`: 'ggplot' object. A line plot showing tenure.
#' - `"data_cleaned"`: data frame filtered only by rows with tenure values
#' lying within the threshold.
#' - `"data_dirty"`: data frame filtered only by rows with tenure values
#' lying outside the threshold.
#' - `"data"`: data frame with the `PersonId` and a calculated variable called
#' `TenureYear` is returned.
#'
#'
#' @examples
#' library(dplyr)
#' # Add HireDate to sq_data
#' sq_data2 <-
#' sq_data %>%
#' mutate(HireDate = as.Date("1/1/2015", format = "%m/%d/%Y"))
#'
#' identify_tenure(sq_data2)
#'
#' @export
identify_tenure <- function(data,
end_date = "Date",
beg_date = "HireDate",
maxten = 40,
return = "message"){
required_variables <- c("HireDate")
## Error message if variables are not present
## Nothing happens if all present
data %>%
check_inputs(requirements = required_variables)
data_prep <-
data %>%
mutate(Date = as.Date(Date, format= "%m/%d/%Y"), # Re-format `Date`
end_date = as.Date(!!sym(end_date), format= "%m/%d/%Y"), # Access a symbol, not a string
beg_date = as.Date(!!sym(beg_date), format= "%m/%d/%Y")) %>% # Access a symbol, not a string
arrange(end_date) %>%
mutate(End = last(end_date))
last_date <- data_prep$End
# graphing data
tenure_summary <-
data_prep %>%
filter(Date == last_date) %>%
mutate(tenure_years = (Date - beg_date)/365) %>%
group_by(tenure_years)%>%
summarise(n = n(),.groups = 'drop')
# off person IDs
oddpeople <-
data_prep %>%
filter(Date == last_date) %>%
mutate(tenure_years = (Date - beg_date)/365) %>%
filter(tenure_years >= maxten) %>%
select(PersonId)
# message
Message <- paste0("The mean tenure is ",round(mean(tenure_summary$tenure_years,na.rm = TRUE),1)," years.\nThe max tenure is ",
round(max(tenure_summary$tenure_years,na.rm = TRUE),1),".\nThere are ",
length(tenure_summary$tenure_years[tenure_summary$tenure_years>=maxten])," employees with a tenure greater than ",maxten," years.")
if(return == "text"){
return(Message)
} else if(return == "message"){
message(Message)
} else if(return == "plot"){
suppressWarnings(
ggplot(data = tenure_summary,aes(x = as.numeric(tenure_years))) +
geom_density() +
labs(title = "Tenure - Density",
subtitle = "Calculated with `HireDate`") +
xlab("Tenure in Years") +
ylab("Density - number of employees") +
theme_wpa_basic()
)
} else if(return == "data_cleaned"){
return(data %>% filter(!(PersonId %in% oddpeople$PersonId)) %>% data.frame())
} else if(return == "data_dirty"){
return(data %>% filter((PersonId %in% oddpeople$PersonId)) %>% data.frame())
} else if(return == "data"){
data_prep %>%
filter(Date == last_date) %>%
mutate(TenureYear = as.numeric((Date - beg_date)/365)) %>%
select(PersonId, TenureYear)
} else {
stop("Error: please check inputs for `return`")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/identify_tenure.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Read a Workplace Analytics query in '.csv' using and create a '.fst'
#' file in the same directory for faster reading
#'
#' @description Uses `import_wpa()` to read a Workplace Analytics query in
#' '.csv' and convert this into the serialized '.csv' format which is much
#' faster to read. The 'fst' package must be installed, or an error message is
#' returned.
#'
#' @details
#' The [fst](https://www.fstpackage.org/) package provides a way to serialize
#' data frames in R which makes loading data much faster than CSV.
#' `import_to_fst()` converts a CSV file into a FST file in the specified
#' directory.
#'
#' Once this FST file is created, it can be read into R using
#' `fst::read_fst()`. Since `import_to_fst()` only does conversion but not
#' loading, it should normally only be run once at the beginning of each piece
#' of analysis, and `fst::read_fst()` should take over the job of data loading
#' at the start of your analysis script.
#'
#' Internally, `import_to_fst()` uses `import_wpa()`, and additional arguments
#' to `import_wpa()` can be passed with `...`.
#'
#' @param path String containing the path to the Workplace Analytics query to be
#' imported. The input file must be a CSV file, and the file extension must be
#' explicitly entered, e.g. `"/files/standard query.csv"`. The converted FST
#' file will be saved in the same directory with a different file extension.
#' @param ... Additional arguments to pass to `import_wpa()`.
#'
#' @return
#' There is no return value. A file with '.fst' extension is written to the same
#' directory where the '.csv' file is read in.
#'
#' @family Import and Export
#'
#' @export
import_to_fst <- function(path, ...){
# Check if fst is installed
check_pkg_installed(pkgname = "fst")
temp_df <- import_wpa(path, ...)
path_fst <- gsub(pattern = "csv$",
replacement = "fst",
x = path)
fst::write_fst(temp_df, path_fst)
message("\nFST file sucessfully created at ", path_fst, ".")
message("\nYou can now load the FST file with `fst::read_fst()`.")
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/import_to_fst.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Import a Workplace Analytics Query
#'
#' @description
#' Import a Workplace Analytics Query from a local CSV File, with variable
#' classifications optimised for other 'wpa' functions.
#'
#' @details
#' `import_wpa()` uses `data.table::fread()` to import CSV files for speed,
#' and by default `stringsAsFactors` is set to FALSE.
#' A data frame is returned by the function (not a `data.table`).
#'
#' @param x String containing the path to the Workplace Analytics query to be
#' imported. The input file must be a CSV file, and the file extension must be
#' explicitly entered, e.g. `"/files/standard query.csv"`
#' @param standardise logical. If TRUE, `import_wpa()` runs `standardise_pq()`
#' to make a Collaboration Assessment query's columns name standard and
#' consistent with a Standard Person Query. Note that this will have no effect
#' if the query being imported is not a Ways of Working Assessment query.
#' Defaults as FALSE.
#' @param encoding String to specify encoding to be used within
#' `data.table::fread()`. See `data.table::fread()` documentation for more
#' information. Defaults to `'UTF-8'`.
#'
#' @return A `tibble` is returned.
#'
#' @family Import and Export
#'
#' @export
import_wpa <- function(x,
standardise = FALSE,
encoding = 'UTF-8'){
return_data <-
data.table::fread(x,
stringsAsFactors = FALSE,
encoding = encoding) %>%
as.data.frame()
# Columns which are Dates
dateCols <- sapply(return_data, function(x) all(is_date_format(x)))
dateCols <- dateCols[dateCols == TRUE]
return_data <-
return_data %>%
dplyr::mutate_at(dplyr::vars(names(dateCols)), ~as.Date(., format = "%m/%d/%Y"))
message("Query has been imported successfully!")
## Query check only available for Person Queries
if(identify_query(return_data) == "Person Query"){
check_query(return_data)
}
## Standardise query if `standardise == TRUE`
if(standardise == TRUE & identify_query(return_data) == "Ways of Working Assessment Query"){
message("Standardising column names for a Ways of Working Assessment query to
a Person query...")
return_data <- standardise_pq(return_data)
}
dplyr::as_tibble(return_data)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/import_wpa.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
.onAttach <- function(libname, pkgname) {
message <- c("\n Thank you for using the {wpa} R package!",
"\n \n Our analysts have taken every care to ensure that this package runs smoothly and bug-free.",
"\n \n However, if you do happen to encounter any, please report any issues at",
"\n https://github.com/microsoft/wpa/issues/",
"\n \n Happy coding!")
packageStartupMessage(message)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/init.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Plot Internal Network Breadth and Size as a scatter plot
#'
#' @description
#' Plot the internal network metrics for a HR variable as a scatter plot,
#' showing Internal Network Breadth as the vertical axis and Internal Network
#' Size as the horizontal axis.
#'
#' @details
#' Uses the metrics `Internal_network_size` and
#' `Networking_outside_organization`.
#'
#' @inheritParams create_bubble
#'
#' @examples
#' \donttest{
#' # Return plot
#' internal_network_plot(sq_data, return = "plot")
#'
#' # Return summary table
#' internal_network_plot(sq_data, return = "table")
#' }
#'
#' @family Visualization
#' @family Network
#'
#' @return
#' 'ggplot' object showing a bubble plot with internal network size as the
#' x-axis and internal network breadth as the y-axis. The size of the bubbles
#' represent the number of unique employees in each group.
#'
#' @export
internal_network_plot <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot",
bubble_size = c(1, 8)) {
data %>%
rename(`Internal Network Size` = "Internal_network_size",
`Internal Network Breadth` = "Networking_outside_organization") %>%
create_bubble(hrvar = hrvar,
mingroup = mingroup,
metric_x = "Internal Network Size",
metric_y = "Internal Network Breadth",
return = return,
bubble_size = bubble_size)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/internal_network_plot.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Identify whether string is a date format
#'
#' @description
#' This function uses regular expression to determine whether a string is of the
#' format `"mdy"`, separated by `"-"`, `"/"`, or `"."`, returning a logical
#' vector.
#'
#' @param string Character string to test whether is a date format.
#'
#' @return logical value indicating whether the string is a date format.
#'
#' @examples
#' is_date_format("1/5/2020")
#'
#' @family Support
#'
#' @export
is_date_format <- function(string){
grepl("^\\d{1,2}[- /.]\\d{1,2}[- /.]\\d{1,4}$",
string)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/is_date_format.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Run a summary of Key Metrics from the Standard Person Query data
#'
#' @description
#' Returns a heatmapped table by default, with options to return a table.
#'
#' @template spq-params
#' @param metrics A character vector containing the variable names to calculate
#' averages of.
#' @param return Character vector specifying what to return, defaults to "plot".
#' Valid inputs are "plot" and "table".
#' @param low String specifying colour code to use for low-value metrics.
#' Arguments are passed directly to `ggplot2::scale_fill_gradient2()`.
#' @param mid String specifying colour code to use for mid-value metrics.
#' Arguments are passed directly to `ggplot2::scale_fill_gradient2()`.
#' @param high String specifying colour code to use for high-value metrics.
#' Arguments are passed directly to `ggplot2::scale_fill_gradient2()`.
#' @param textsize A numeric value specifying the text size to show in the plot.
#'
#' @import dplyr
#' @import ggplot2
#' @import reshape2
#' @importFrom stats reorder
#'
#' @return
#' Returns a ggplot object by default, when `'plot'` is passed in `return`.
#' When `'table'` is passed, a summary table is returned as a data frame.
#'
#' @family Visualization
#'
#' @examples
#' \donttest{
#' # Heatmap plot is returned by default
#' keymetrics_scan(sq_data)
#'
#' # Heatmap plot with custom colours
#' keymetrics_scan(sq_data, low = "purple", high = "yellow")
#'
#' # Return summary table
#' keymetrics_scan(sq_data, hrvar = "LevelDesignation", return = "table")
#' }
#'
#' @export
keymetrics_scan <- function(data,
hrvar = "Organization",
mingroup = 5,
metrics = c("Workweek_span",
"Collaboration_hours",
"After_hours_collaboration_hours",
"Meetings",
"Meeting_hours",
"After_hours_meeting_hours",
"Low_quality_meeting_hours",
"Meeting_hours_with_manager_1_on_1",
"Meeting_hours_with_manager",
"Emails_sent",
"Email_hours",
"After_hours_email_hours",
"Generated_workload_email_hours",
"Total_focus_hours",
"Internal_network_size",
"Networking_outside_organization",
"External_network_size",
"Networking_outside_company"),
return = "plot",
low = rgb2hex(7, 111, 161),
mid = rgb2hex(241, 204, 158),
high = rgb2hex(216, 24, 42),
textsize = 2){
## Handling NULL values passed to hrvar
if(is.null(hrvar)){
data <- totals_col(data)
hrvar <- "Total"
}
## Omit if metrics do not exist in dataset
metrics <- dplyr::intersect(metrics, names(data))
## Summary table
myTable <-
data %>%
rename(group = !!sym(hrvar)) %>% # Rename HRvar to `group`
group_by(group, PersonId) %>%
summarise_at(vars(metrics), ~mean(., na.rm = TRUE)) %>%
group_by(group) %>%
summarise_at(vars(metrics), ~mean(., na.rm = TRUE)) %>%
left_join(hrvar_count(data, hrvar = hrvar, return = "table") %>%
rename(Employee_Count = "n"),
by = c("group" = hrvar)) %>%
filter(Employee_Count >= mingroup) # Keep only groups above privacy threshold
myTable %>%
reshape2::melt(id.vars = "group") %>%
reshape2::dcast(variable ~ group) -> myTable_wide
myTable_long <- reshape2::melt(myTable, id.vars=c("group")) %>%
mutate(variable = factor(variable)) %>%
group_by(variable) %>%
# Heatmap by row
mutate(value_rescaled = maxmin(value)) %>%
ungroup()
plot_object <-
myTable_long %>%
filter(variable != "Employee_Count") %>%
ggplot(aes(x = group,
y = stats::reorder(variable, desc(variable)))) +
geom_tile(aes(fill = value_rescaled),
colour = "#FFFFFF",
size = 2) +
geom_text(aes(label=round(value, 1)), size = textsize) +
# Fill is contingent on max-min scaling
scale_fill_gradient2(low = low,
mid = mid,
high = high,
midpoint = 0.5,
breaks = c(0, 0.5, 1),
labels = c("Minimum", "", "Maximum"),
limits = c(0, 1)) +
scale_x_discrete(position = "top") +
scale_y_discrete(labels = us_to_space) +
theme_wpa_basic() +
theme(axis.line = element_line(color = "#FFFFFF")) +
labs(title = "Key metrics",
subtitle = paste("Weekly average by", camel_clean(hrvar)),
y =" ",
x =" ",
fill = " ",
caption = extract_date_range(data, return = "text")) +
theme(axis.text.x = element_text(angle = 90, hjust = 0),
plot.title = element_text(color="grey40", face="bold", size=20))
if(return == "table"){
myTable_wide %>%
as_tibble() %>%
return()
} else if(return == "plot"){
return(plot_object)
} else {
stop("Please enter a valid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/keymetrics_scan.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Run a summary of Key Metrics without aggregation
#'
#' @description
#' Return a heatmapped table directly from the aggregated / summarised data.
#' Unlike `keymetrics_scan()` which performs a person-level aggregation, there
#' is no calculation for `keymetrics_scan_asis()` and the values are rendered as
#' they are passed into the function.
#'
#' @param data data frame containing data to plot. It is recommended to provide
#' data in a 'long' table format where one grouping column forms the rows, a
#' second column forms the columns, and a third numeric columns forms the
#' @param row_var String containing name of the grouping variable that will form
#' the rows of the heatmapped table.
#' @param col_var String containing name of the grouping variable that will form
#' the columns of the heatmapped table.
#' @param group_var String containing name of the grouping variable by which
#' heatmapping would apply. Defaults to `col_var`.
#' @param value_var String containing name of the value variable that will form
#' the values of the heatmapped table. Defaults to `"value"`.
#' @param title Title of the plot.
#' @param subtitle Subtitle of the plot.
#' @param caption Caption of the plot.
#' @param ylab Y-axis label for the plot (group axis)
#' @param xlab X-axis label of the plot (bar axis).
#' @param rounding Numeric value to specify number of digits to show in data
#' labels
#' @param low String specifying colour code to use for low-value metrics.
#' Arguments are passed directly to `ggplot2::scale_fill_gradient2()`.
#' @param mid String specifying colour code to use for mid-value metrics.
#' Arguments are passed directly to `ggplot2::scale_fill_gradient2()`.
#' @param high String specifying colour code to use for high-value metrics.
#' Arguments are passed directly to `ggplot2::scale_fill_gradient2()`.
#' @param textsize A numeric value specifying the text size to show in the plot.
#'
#' @return
#' ggplot object for a heatmap table.
#'
#' @examples
#'
#' library(dplyr)
#'
#' # Compute summary table
#' out_df <-
#' sq_data %>%
#' group_by(Organization) %>%
#' summarise(
#' across(
#' .cols = c(
#' Workweek_span,
#' Collaboration_hours
#' ),
#' .fns = ~median(., na.rm = TRUE)
#' ),
#' .groups = "drop"
#' ) %>%
#' tidyr::pivot_longer(
#' cols = c("Workweek_span", "Collaboration_hours"),
#' names_to = "metrics"
#' )
#'
#' keymetrics_scan_asis(
#' data = out_df,
#' col_var = "metrics",
#' row_var = "Organization"
#' )
#'
#' # Show data the other way round
#' keymetrics_scan_asis(
#' data = out_df,
#' col_var = "Organization",
#' row_var = "metrics",
#' group_var = "metrics"
#' )
#'
#' @export
#'
keymetrics_scan_asis <- function(
data,
row_var,
col_var,
group_var = col_var,
value_var = "value",
title = NULL,
subtitle = NULL,
caption = NULL,
ylab = row_var,
xlab = "Metrics",
rounding = 1,
low = rgb2hex(7, 111, 161),
mid = rgb2hex(241, 204, 158),
high = rgb2hex(216, 24, 42),
textsize = 2
){
# Transform to long data format
myTable_long <-
data %>%
mutate(!!sym(group_var) := factor(!!sym(group_var))) %>%
group_by(!!sym(group_var)) %>%
# Heatmap by row
mutate(value_rescaled = maxmin(!!sym(value_var))) %>%
ungroup()
plot_object <-
myTable_long %>%
ggplot(aes(x = !!sym(row_var),
y = stats::reorder(!!sym(col_var), desc(!!sym(col_var))))) +
geom_tile(aes(fill = value_rescaled),
colour = "#FFFFFF",
size = 2) +
geom_text(aes(label = round(value, rounding)), size = textsize) +
# Fill is contingent on max-min scaling
scale_fill_gradient2(
low = low,
mid = mid,
high = high,
midpoint = 0.5,
breaks = c(0, 0.5, 1),
labels = c("Minimum", "", "Maximum"),
limits = c(0, 1)
) +
scale_x_discrete(position = "top") +
scale_y_discrete(labels = us_to_space) +
theme_wpa_basic() +
theme(axis.line = element_line(color = "#FFFFFF")) +
labs(title = title,
subtitle = subtitle,
y = " ",
x = " ",
fill = " ",
caption = caption) +
theme(
axis.text.x = element_text(angle = 90, hjust = 0),
plot.title = element_text(color="grey40", face="bold", size=20)
)
plot_object
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/keymetrics_scan_asis.R
|
#' @title Max-Min Scaling Function
#'
#' @description This function allows you to scale vectors or an entire data
#' frame using the max-min scaling method A numeric vector is always returned.
#'
#' @details This is used within `keymetrics_scan()` to enable row-wise
#' heatmapping. Originally implemented in
#' <https://github.com/martinctc/surveytoolbox>.
#'
#' @param x Pass a vector or the required columns of a data frame through this
#' argument.
#' @keywords max-min
#'
#' @family Support
#'
#' @examples
#' numbers <- c(15, 40, 10, 2)
#' maxmin(numbers)
#'
#' @return
#' Returns a numeric vector with the input rescaled.
#'
#' @export
maxmin <- function(x){
if(any(is.na(x))){
warning("Warning: vector contains missing values. Those values will return as NA.")
}
maxs <- max(x, na.rm = TRUE)
mins <- min(x, na.rm = TRUE)
as.numeric(scale(x,center=mins,scale=maxs-mins))
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/maxmin.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Distribution of Meeting Hours as a 100% stacked bar
#'
#' @description
#' Analyze Meeting Hours distribution.
#' Returns a stacked bar plot by default.
#' Additional options available to return a table with distribution elements.
#'
#' @inheritParams create_dist
#' @inherit create_dist return
#'
#' @family Visualization
#' @family Meetings
#'
#' @examples
#' # Return plot
#' meeting_dist(sq_data, hrvar = "Organization")
#'
#' # Return summary table
#' meeting_dist(sq_data, hrvar = "Organization", return = "table")
#'
#' # Return result with a custom specified breaks
#' meeting_dist(sq_data, hrvar = "LevelDesignation", cut = c(4, 7, 9))
#'
#' @export
meeting_dist <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot",
cut = c(5, 10, 15)) {
create_dist(data = data,
metric = "Meeting_hours",
hrvar = hrvar,
mingroup = mingroup,
return = return,
cut = cut)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/meeting_dist.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Extract top low-engagement meetings from the Meeting Query
#'
#' @description
#' Pass a Standard Meeting Query and extract the top low engagement meetings.
#'
#' @param data Data frame containing a Standard Meeting Query to pass through.
#' @param recurring_only Logical value indicating whether to only filter by
#' recurring meetings.
#' @param top_n Numeric value for the top number of results to return in the
#' output.
#' @param fte_month Numeric value for the assumed number of employee hours per
#' month for conversion calculations. Defaults to 180.
#' @param fte_week Numeric value for the assumed number of employee hours per
#' week for conversion calculations. Defaults to 180.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"table"`
#' - `"data"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"table"`: data frame. A summary table containing the top `n` low
#' engagement meetings
#' - `"data"`: data frame. Contains the full computed metrics related to the
#' top `n` low engagement meetings
#'
#' @import dplyr
#' @importFrom data.table ":=" "%like%" "%between%"
#'
#' @family Meetings
#'
#' @examples
#' meeting_extract(mt_data,
#' recurring_only = FALSE,
#' top_n = 10,
#' return = "table")
#'
#' @export
meeting_extract <- function(data,
recurring_only = TRUE,
top_n = 30,
fte_month = 180,
fte_week = 40,
return = "table"){
if(recurring_only == TRUE){
data <- filter(data, IsRecurring == TRUE)
}
mq_dt <-
data %>%
mutate(Emails_sent_per_attendee_hour =
Emails_sent_during_meetings / Attendee_meeting_hours) %>%
mutate(AttendanceRate = Attendees / Invitees) %>%
data.table::as.data.table()
mq_df <-
mq_dt %>%
.[,
.(
Subject = first(Subject), # First instance
Sum_Attendee_meeting_hours = sum(Attendee_meeting_hours),
Mean_Attendee_meeting_hours = mean(Attendee_meeting_hours),
Sum_Attendees = sum(Attendees),
Mean_Attendees = mean(Attendees),
Sum_Emails_sent_during_meetings = sum(Emails_sent_during_meetings),
Mean_Emails_sent_during_meetings = mean(Emails_sent_during_meetings),
Sum_Emails_sent_per_attendee_hour = sum(Emails_sent_per_attendee_hour),
Mean_Emails_sent_per_attendee_hour = mean(Emails_sent_per_attendee_hour),
Sum_DurationHours = sum(DurationHours),
Mean_DurationHours = mean(DurationHours),
Sum_Total_meeting_cost = sum(Total_meeting_cost),
Mean_Total_meeting_cost = mean(Total_meeting_cost),
Mean_AttendanceRate = mean(AttendanceRate),
Mean_Invitees = mean(Invitees),
NRecurring = .N # Number of recurrences
),
by = MeetingId] %>%
.[Mean_Emails_sent_per_attendee_hour >= 2] %>%
.[order(-Sum_Attendee_meeting_hours)] %>%
slice(1:top_n) %>%
as.data.frame()
if(return == "data"){
mq_df
} else if(return == "table"){
mq_df %>%
select(Subject,
`Attendee hours` = "Sum_Attendee_meeting_hours",
`Average emails per attendee hour` = "Mean_Emails_sent_per_attendee_hour",
`Duration` = Mean_DurationHours,
`Attendees` = Mean_Attendees,
`Number of recurrences` = NRecurring,
`Average Attendance Rate` = Mean_AttendanceRate,
`Invitees` = Mean_Invitees) %>%
mutate(`Equivalent FTE month` = `Attendee hours` / 180) %>%
mutate(`Equivalent FTE week` = `Attendee hours` / 40)
} else {
stop("Invalid input to `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/meeting_extract.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Distribution of Meeting Hours (Fizzy Drink plot)
#'
#' @description
#' Analyze weekly meeting hours distribution, and returns a 'fizzy' scatter plot
#' by default. Additional options available to return a table with distribution
#' elements.
#'
#' @details
#' Uses the metric `Meeting_hours`.
#'
#' @inheritParams create_fizz
#' @inherit create_fizz return
#'
#' @family Visualization
#' @family Meetings
#'
#' @examples
#' # Return plot
#' meeting_fizz(sq_data, hrvar = "Organization", return = "plot")
#'
#' # Return summary table
#' meeting_fizz(sq_data, hrvar = "Organization", return = "table")
#' @export
meeting_fizz <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot"){
create_fizz(data = data,
metric = "Meeting_hours",
hrvar = hrvar,
mingroup = mingroup,
return = return)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/meeting_fizz.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Meeting Time Trend - Line Chart
#'
#' @description
#' Provides a week by week view of meeting time, visualised as line charts.
#' By default returns a line chart for meeting hours,
#' with a separate panel per value in the HR attribute.
#' Additional options available to return a summary table.
#'
#' @inheritParams create_line
#' @inherit create_line return
#'
#' @family Visualization
#' @family Meetings
#'
#' @examples
#' # Return a line plot
#' meeting_line(sq_data, hrvar = "LevelDesignation")
#'
#' # Return summary table
#' meeting_line(sq_data, hrvar = "LevelDesignation", return = "table")
#'
#' @export
meeting_line <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot"){
## Inherit arguments
create_line(data = data,
metric = "Meeting_hours",
hrvar = hrvar,
mingroup = mingroup,
return = return)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/meeting_line.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Run a meeting habits / meeting quality analysis
#'
#' @description Return an analysis of Meeting Quality with a bubble plot, using
#' a Standard Person Query as an input.
#'
#' @inheritParams create_bubble
#'
#' @param metric_x String specifying which variable to show in the x-axis when
#' returning a plot. Must be one of the following:
#' - `"Low_quality_meeting_hours"` (default)
#' - `"After_hours_meeting_hours"`
#' - `"Conflicting_meeting_hours"`
#' - `"Multitasking_meeting_hours"`
#' - Any _meeting hour_ variable that can be divided by `Meeting_hours`
#'
#' If the provided metric name is not found in the data, the function will use
#' the first matched metric from the above list.
#'
#' @inherit create_bubble return
#'
#' @import dplyr
#'
#' @family Visualization
#' @family Meetings
#'
#' @examples
#' # Return plot
#' meeting_quality(sq_data, return = "plot")
#'
#' # Return plot - showing multi-tasking %
#' \donttest{
#' meeting_quality(sq_data,
#' metric_x = "Multitasking_meeting_hours",
#' return = "plot")
#' }
#'
#' # Return summary table
#' \donttest{
#' meeting_quality(sq_data, return = "table")
#' }
#'
#' @export
meeting_quality <- function(data,
hrvar = "Organization",
metric_x = "Low_quality_meeting_hours",
mingroup = 5,
return = "plot"){
## Check whether provided metric is available
metric_vec <- c(
"Low_quality_meeting_hours",
"After_hours_meeting_hours",
"Conflicting_meeting_hours",
"Multitasking_meeting_hours"
)
if(!(metric_x %in% names(data))){
metric_x <- dplyr::intersect(metric_vec, names(data))[1]
message(
glue::glue(
"Using {metric_x} instead due to missing variables in input data."
)
)
}
## Wrapper around summary table
if(return == "table"){
meeting_chr <-
c("After_hours_meeting_hours",
"Low_quality_meeting_hours",
"Conflicting_meeting_hours",
"Multitasking_meeting_hours",
"Meetings",
"Meeting_hours",
metric_x) %>%
unique() %>%
dplyr::intersect(names(data)) # Use only available metrics
data %>%
rename(group = !!sym(hrvar)) %>% # Rename hrvar to `group`
group_by(PersonId, group) %>%
summarise_at(vars(meeting_chr), ~mean(., na.rm = TRUE)) %>%
group_by(group) %>%
summarise_at(vars(meeting_chr), ~mean(., na.rm = TRUE)) %>%
left_join(hrvar_count(data, hrvar, return = "table"), by = c("group" = hrvar)) %>%
filter(n >= mingroup)
} else {
percent_str <- NULL
percent_str <- paste0("Percentage_of_", metric_x)
data %>%
mutate(!!sym(percent_str) := !!sym(metric_x) / Meeting_hours) %>%
create_bubble(hrvar = hrvar,
mingroup = mingroup,
metric_x = percent_str,
metric_y = "Meeting_hours",
return = return)
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/meeting_quality.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Meeting Hours Ranking
#'
#' @description
#' This function scans a standard query output for groups with high levels of
#' Weekly Meeting Collaboration. Returns a plot by default, with an option to
#' return a table with a all of groups (across multiple HR attributes) ranked by
#' hours of digital collaboration.
#'
#' @details
#' Uses the metric `Meeting_hours`.
#' See `create_rank()` for applying the same analysis to a different metric.
#'
#' @inheritParams create_rank
#' @inherit create_rank return
#'
#' @family Visualization
#' @family Meetings
#'
#' @examples
#' # Return rank table
#' meeting_rank(
#' data = sq_data,
#' return = "table"
#' )
#'
#' # Return plot
#' meeting_rank(
#' data = sq_data,
#' return = "plot"
#' )
#'
#' @export
meeting_rank <- function(data,
hrvar = extract_hr(data),
mingroup = 5,
mode = "simple",
plot_mode = 1,
return = "plot"){
data %>%
create_rank(metric = "Meeting_hours",
hrvar = hrvar,
mingroup = mingroup,
mode = mode,
plot_mode = plot_mode,
return = return)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/meeting_rank.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Produce a skim summary of meeting hours
#'
#' @description
#' This function returns a skim summary in the console
#' when provided a standard query in the input.
#'
#' @param data A standard person query data in the form of a data frame.
#'
#' @param return String specifying what to return. This must be one of the following strings:
#' - `"message"`
#' - `"text"`
#' - `"table"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return` argument:
#' - `"message"`: message in console.
#' - `"text"`: string.
#' - `"table"`: data frame.
#'
#' @import dplyr
#'
#' @family Meetings
#'
#' @examples
#' meeting_skim(sq_data)
#'
#' @export
meeting_skim <- function(data, return = "message"){
required_vars <-
c(
"PersonId",
"Meeting_hours",
"Conflicting_meeting_hours",
"Multitasking_meeting_hours",
"Redundant_meeting_hours__lower_level_",
"Redundant_meeting_hours__organizational_",
"Low_quality_meeting_hours"
)
used_vars <- dplyr::intersect(names(data), required_vars)
key_output <-
data %>%
select(used_vars) %>%
summarise_at(vars(-PersonId), ~sum(.)) %>% # sum total
tidyr::gather(HourType, Hours, -Meeting_hours) %>%
mutate_at(vars(Hours), ~./Meeting_hours) %>%
mutate(RawHours = Hours * Meeting_hours)
mh_total <- round(key_output$Meeting_hours[1])
mh_lowqualityprop <-
key_output %>%
filter(HourType == "Low_quality_meeting_hours") %>%
pull(Hours) %>%
`*`(100) %>%
round() %>%
paste0("%")
bracket <- function(text){
paste0("(", text, ")")
}
extract_prop <- function(filt_chr){
key_output %>%
filter(HourType == filt_chr) %>%
pull(Hours) %>%
`*`(100) %>%
round() %>%
paste0("%")
}
extract_raw <- function(filt_chr){
key_output %>%
filter(HourType == filt_chr) %>%
pull(RawHours) %>%
round()
}
combine_extracts <- function(filt_chr, keyword){
out <-
key_output %>%
filter(HourType == filt_chr)
if(nrow(out) == 0){
return(NULL)
} else {
paste(
">>>",
extract_raw(filt_chr),
"are",
keyword,
bracket(extract_prop(filt_chr))
)
}
}
key_text <- c(
combine_extracts(filt_chr = "Low_quality_meeting_hours",
keyword = "low quality"),
combine_extracts(filt_chr = "Redundant_meeting_hours__organizational_",
keyword = "redundant"),
combine_extracts(filt_chr = "Conflicting_meeting_hours",
keyword = "conflicting"),
combine_extracts(filt_chr = "Multitasking_meeting_hours",
keyword = "multitasking")
) %>%
.[nchar(.) >= 1] %>% # at least character length >= 1
paste(collapse = "\n")
print_text <-
paste(
paste(
"There are",
mh_total,
"total meeting hours across the analysis population."
),
key_text,
sep = "\n"
)
if(return == "message"){
message(print_text)
} else if(return == "text"){
print_text <- gsub(pattern = ">>>", replacement = " - ", x = print_text)
print_text
} else if(return == "table"){
key_output
} else {
stop("Please check `return`")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/meeting_skim.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Meeting Summary
#'
#' @description
#' Provides an overview analysis of weekly meeting hours.
#' Returns a bar plot showing average weekly meeting hours by default.
#' Additional options available to return a summary table.
#'
#' @inheritParams create_bar
#' @inherit create_bar return
#'
#' @family Visualization
#' @family Meetings
#'
#' @examples
#' # Return a ggplot bar chart
#' meeting_summary(sq_data, hrvar = "LevelDesignation")
#'
#' # Return a summary table
#' meeting_summary(sq_data, hrvar = "LevelDesignation", return = "table")
#'
#' @export
meeting_summary <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot"){
create_bar(data = data,
metric = "Meeting_hours",
hrvar = hrvar,
mingroup = mingroup,
return = return,
bar_colour = "default")
}
#' @rdname meeting_summary
#' @export
meeting_sum <- meeting_summary
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/meeting_summary.R
|
#' @title Generate a Meeting Text Mining report in HTML
#'
#' @description
#' Create a text mining report in HTML based on Meeting Subject Lines
#'
#' @param data A Meeting Query dataset in the form of a data frame.
#' @param path Pass the file path and the desired file name, _excluding the file
#' extension_. For example, `"meeting text mining report"`.
#' @param stopwords A character vector OR a single-column data frame labelled
#' `'word'` containing custom stopwords to remove.
#' @param timestamp Logical vector specifying whether to include a timestamp in
#' the file name. Defaults to TRUE.
#' @param keep A numeric vector specifying maximum number of words to keep.
#' @param seed A numeric vector to set seed for random generation.
#'
#' @family Reports
#' @family Meetings
#' @family Text-mining
#'
#' @inherit generate_report return
#'
#' @export
meeting_tm_report <- function(data,
path = "meeting text mining report",
stopwords = NULL,
timestamp = TRUE,
keep = 100,
seed = 100){
## Check if dependencies are installed
check_pkg_installed(pkgname = "flexdashboard")
## Add timestamp
if(timestamp == TRUE){
path <- paste(path, tstamp())
}
## Generate report from RMarkdown
generate_report2(
data = data,
stopwords = stopwords,
keep = keep,
seed = seed,
output_file = paste0(path, ".html"),
report_title = "Analysis of Meeting Subject Lines",
rmd_dir = system.file("rmd_template/meeting_tm/meeting_tm_report.rmd", package = "wpa"),
output_format =
flexdashboard::flex_dashboard(orientation = "columns",
vertical_layout = "fill",
source_code = "embed"),
)
# ## Create timestamped path (if applicable)
# if(timestamp == TRUE){
# newpath <- paste(path, wpa::tstamp())
# } else {
# newpath <- path
# }
#
# # Set outputs
# output_list <-
# list(
# md2html(text = read_preamble("blank.md")), # Header
# data %>% tm_wordcloud(stopwords = stopwords, keep = keep),
# data %>% tm_freq(token = "words", stopwords = stopwords, keep = keep),
# data %>% tm_freq(token = "words", stopwords = stopwords, keep = keep, return = "table"),
# data %>% tm_freq(token = "ngrams", stopwords = stopwords, keep = keep),
# data %>% tm_freq(token = "ngrams", stopwords = stopwords, keep = keep, return = "table"),
# data %>% tm_cooc(stopwords = stopwords, seed = seed),
# data %>% tm_cooc(stopwords = stopwords, seed = seed, return = "table"),
# data %>% subject_scan(mode = "days"),
# data %>% subject_scan(mode = "hours")
# ) %>%
# purrr::map_if(is.data.frame, create_dt)
#
# # Set header titles
# title_list <-
# c(
# "Text Mining Report", # Section header
# "Word cloud",
# "Word Frequency",
# "",
# "Phrase Frequency",
# "",
# "Word Co-occurrence",
# "",
# "Top terms",
# ""
# )
#
# # Set header levels
# n_title <- length(title_list)
# levels_list <- rep(3, n_title)
# levels_list[c(1)] <- 2 # Section header
#
# # Generate report
# generate_report(title = "Analysis of Meeting Subject Lines",
# filename = newpath,
# outputs = output_list,
# titles = title_list,
# subheaders = rep("", n_title),
# echos = rep(FALSE, n_title),
# levels = levels_list,
# theme = "cosmo",
# preamble = read_preamble("meeting_tm_report.md"))
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/meeting_tm_report.R
|
#' @title Meeting Hours Time Trend
#'
#' @description
#' Provides a week by week view of meeting time. By default returns a week by
#' week heatmap, highlighting the points in time with most activity. Additional
#' options available to return a summary table.
#'
#' @details
#' Uses the metric `Meeting_hours`.
#'
#' @inheritParams create_trend
#' @inherit create_trend return
#'
#' @family Visualization
#' @family Meetings
#'
#' @export
meeting_trend <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot"){
create_trend(data,
metric = "Meeting_hours",
hrvar = hrvar,
mingroup = mingroup,
return = return)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/meeting_trend.R
|
#' @title Distribution of Meeting Types by number of Attendees and Duration
#'
#' @description Calculate the hour distribution of internal meeting types. This
#' is a wrapper around `meetingtype_dist_mt()` and `meetingtype_dist_ca()`,
#' depending on whether a Meeting Query or a Ways of Working Assessment Query is
#' passed as an input.
#'
#' @param data Data frame. If a meeting query, must contain the variables
#' `Attendee` and `DurationHours`.
#' @param hrvar Character string to specify the HR attribute to split the data
#' by. Note that this is only applicable if a Ways of Working Assessment query
#' is passed to the function. If a Meeting Query is passed instead, this
#' argument is ignored.
#' @param mingroup Numeric value setting the privacy threshold / minimum group
#' size. Defaults to 5. Only applicable when using a Ways of Working
#' Assessment query.
#'
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: ggplot object. A matrix of meeting types with duration and the
#' number of attendees. If using a Ways of Working Assessment query with
#' `meetingtype_dist_ca()` and an HR attribute with more than one unique value
#' is passed to `hrvar`, a stacked bar plot is returned.
#' - `"table"`: data frame. A summary table.
#'
#' @import ggplot2
#' @import dplyr
#' @importFrom stats setNames
#'
#' @family Visualization
#' @family Meetings
#'
#' @examples
#' # Implementation using Standard Meeting Query
#' meetingtype_dist(mt_data)
#'
#' @export
meetingtype_dist <- function(data,
hrvar = NULL,
mingroup = 5,
return = "plot"){
if("MeetingId" %in% names(data)){
message("Calculating results using a Meeting Query...")
meetingtype_dist_mt(data, return = return)
} else if("PersonId" %in% names(data)){
message("Calculating results using a Ways of Working Assessment Query...")
meetingtype_dist_ca(data, hrvar = hrvar, mingroup = mingroup, return = return)
} else {
stop("Please check query type. Must be either a Ways of Working Assessment Query or a Meeting Query.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/meetingtype_dist.R
|
#' @title Meeting Type Distribution (Ways of Working Assessment Query)
#'
#' @description
#' Calculate the hour distribution of internal meeting types, using a Ways of
#' Working Assessment Query with core Workplace Analytics variables as an input.
#'
#' @param data Meeting Query data frame. Must contain the variables `Attendee` and `DurationHours`
#' @param hrvar Character string to specify the HR attribute to split the data by.
#' @param mingroup Numeric value setting the privacy threshold / minimum group size. Defaults to 5.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#'
#' See `Value` for more information.
#'
#' @import ggplot2
#' @import dplyr
#' @importFrom stats setNames
#'
#' @inherit meetingtype_dist return
#'
#' @family Visualization
#' @family Meetings
#'
#' @export
meetingtype_dist_ca <- function(data,
hrvar = NULL,
mingroup = 5,
return = "plot"){
mt_dist_str <- c("Bloated_meeting_hours",
"Lengthy_meeting_hours",
"Workshop_meeting_hours",
"All_hands_meeting_hours",
"Status_update_meeting_hours",
"Decision_making_meeting_hours",
"One_on_one_meeting_hours")
mt_dist_str_clean <-
mt_dist_str %>%
gsub(pattern = "_meeting_hours", replacement = "", x = .) %>%
us_to_space()
## Add dummy "Total" column if hrvar = NULL
if(is.null(hrvar)){
data <- mutate(data, Total = "Total")
hrvar <- "Total"
}
## No org splits
if(hrvar == "Total"){
myResultsTable <-
data %>%
summarise_at(vars(mt_dist_str), ~sum(., na.rm = TRUE)) %>%
gather(MeetingType, AttendeeMeetingHours) %>%
mutate(Prop = AttendeeMeetingHours / sum(AttendeeMeetingHours),
Percent = paste(round(Prop * 100), "%")) %>%
mutate(MeetingType = gsub(pattern = "_meeting_hours", replacement = "", x = MeetingType)) %>%
mutate(MeetingType = us_to_space(MeetingType))
## Only for creating the bottom row data
myResultsTableTotal <-
data %>%
summarise_at(vars(mt_dist_str), ~sum(., na.rm = TRUE)) %>%
gather(MeetingType, AttendeeMeetingHours) %>%
mutate(MeetingType = "Total") %>%
group_by(MeetingType) %>%
summarise(AttendeeMeetingHours = sum(AttendeeMeetingHours, na.rm = TRUE)) %>%
mutate(Prop = AttendeeMeetingHours / sum(AttendeeMeetingHours),
Percent = paste(round(Prop * 100), "%"))
outputTable <-
rbind(myResultsTable,
myResultsTableTotal)
} else {
## Group by hrvar
myResultsTable <-
data %>%
group_by(!!sym(hrvar)) %>%
summarise_at(vars(mt_dist_str), ~sum(., na.rm = TRUE)) %>%
left_join(data %>% hrvar_count(hrvar = hrvar, return = "table"),
by = hrvar) %>%
filter(n >= mingroup) %>%
gather(MeetingType, AttendeeMeetingHours, -!!sym(hrvar), -n) %>%
group_by(!!sym(hrvar)) %>%
mutate(Prop = AttendeeMeetingHours / sum(AttendeeMeetingHours),
Percent = paste(round(Prop * 100), "%")) %>%
mutate(MeetingType = gsub(pattern = "_meeting_hours", replacement = "", x = MeetingType)) %>%
mutate(MeetingType = us_to_space(MeetingType))
outputTable <-
myResultsTable %>%
ungroup() %>%
select(!!sym(hrvar), MeetingType, Prop) %>%
spread(MeetingType, Prop)
}
if(hrvar == "Total"){
base_df <-
data.frame(id = 1:7,
value = c("All hands",
"Bloated",
"Status update",
"Decision making",
"One on one",
"Lengthy",
"Workshop"))
duration <-
c(0, 0, 3, 3,
0, 0, 2, 2,
0, 0, 1, 1,
0, 0, 1, 1,
0, 0, 1, 1,
1, 1, 2, 2,
2, 2, 3, 3)
attendees <-
c(4, 5, 5, 4,
3, 4, 4, 3,
2, 3, 3, 2,
1, 2, 2, 1,
0, 1, 1, 0,
0, 3, 3, 0,
0, 4, 4, 0)
main_plot_df <-
rbind(base_df,
base_df,
base_df,
base_df) %>%
arrange(id) %>%
mutate(Duration = duration,
Attendees = attendees)
label_df <-
main_plot_df %>%
group_by(id, value) %>%
summarise(x = mean(Duration),
y = mean(Attendees)) %>%
mutate(value2 = sub(" ", "\n", value),
text = ifelse(id %in% c(1, 2, 6, 7),"#FFFFFF", "black"),
fill = ifelse(id %in% c(1, 2, 6, 7),"#1d627e", "#34b1e2")) %>%
left_join(select(myResultsTable, MeetingType, Percent),
by = c("value" = "MeetingType")) %>%
mutate(Percent = ifelse(is.na(Percent), "0 %", Percent)) %>%
mutate(value2 = paste(value2, Percent, sep = "\n"))
colo_v <- setNames(label_df$fill, nm = base_df$value)
text_v <- setNames(label_df$text, nm = label_df$value)
plot_object <-
main_plot_df %>%
ggplot(aes(x = Duration, y = Attendees)) +
geom_polygon(aes(fill = value, group = id),
colour = "#FFFFFF") +
scale_fill_manual(values = colo_v) +
geom_text(data = label_df, aes(x = x, y = y, label = value2, colour = value), size = 3) +
scale_colour_manual(values = text_v) +
scale_x_continuous(breaks = 0:3,
labels = c("0", "1", "2+", "")) +
scale_y_continuous(breaks = 0:5,
labels = c("2", "3-8", "9-18",
"19-50", "51+", "")) +
labs(title = "Meeting types by attendees and duration",
subtitle = "% of total time spent in meetings",
ylab = "Attendees",
xlab = "Duration (hours)",
caption = extract_date_range(data, return = "text")) +
theme_wpa_basic() +
theme(legend.position = "none")
} else {
plot_object <-
myResultsTable %>%
mutate(MeetingType = factor(MeetingType, levels = rev(mt_dist_str_clean))) %>%
mutate(Fill = case_when(MeetingType == "Bloated" ~ rgb2hex(180,180,180),
MeetingType == "Lengthy" ~ rgb2hex(120,120,120),
MeetingType == "Workshop" ~ rgb2hex(90,90,90),
MeetingType == "All hands" ~ rgb2hex(60,60,60),
MeetingType == "Status update" ~ rgb2hex(45,160,160),
MeetingType == "Decision making" ~ rgb2hex(25,120,140),
MeetingType == "One on one" ~ rgb2hex(5,85,100))) %>%
ggplot(aes(x = !!sym(hrvar), y = Prop, group = MeetingType, fill = Fill)) +
geom_bar(position = "stack", stat = "identity") +
geom_text(aes(label = paste(round(Prop * 100), "%")),
position = position_stack(vjust = 0.5),
color = "#FFFFFF",
fontface = "bold") +
scale_fill_identity(name = "Coaching styles",
breaks = c(
rgb2hex(180,180,180),
rgb2hex(120,120,120),
rgb2hex(90,90,90),
rgb2hex(60,60,60),
rgb2hex(45,160,160),
rgb2hex(25,120,140),
rgb2hex(5,85,100)
),
labels = mt_dist_str_clean,
guide = "legend") +
coord_flip() +
theme_wpa_basic() +
labs(title = "Meeting types by attendees and duration",
subtitle = "% of total time spent in meetings",
y = "Percentage",
caption = extract_date_range(data, return = "text"))
}
if(return == "table"){
outputTable
} else if(return == "plot"){
return(plot_object)
} else {
stop("Please enter a valid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/meetingtype_dist_ca.R
|
#' @title Meeting Type Distribution (Meeting Query)
#'
#' @description
#' Calculate the hour distribution of internal meeting types, using a Meeting
#' Query with core Workplace Analytics variables as an input.
#'
#' @param data Meeting Query data frame. Must contain the variables `Attendee` and `DurationHours`
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#'
#' See `Value` for more information.
#'
#' @import ggplot2
#' @import dplyr
#' @importFrom stats setNames
#'
#' @inherit meetingtype_dist return
#'
#' @family Visualization
#' @family Meetings
#'
#' @export
meetingtype_dist_mt <- function(data, return = "plot"){
## Date range data frame
myPeriod <- extract_date_range(data)
data_typed <-
data %>%
mutate(MeetingType = case_when(
Attendees == 2 & DurationHours <= 1 ~ "One on one",
Attendees >= 3 & Attendees <= 8 & DurationHours <= 1 ~ "Decision making",
Attendees >= 9 & Attendees <= 18 & DurationHours <= 1 ~ "Status update",
Attendees >= 19 & Attendees <= 50 & DurationHours <= 2 ~ "Bloated",
Attendees <= 18 & DurationHours >= 1 & DurationHours <= 2 ~ "Lengthy",
Attendees >= 51 ~ "All hands",
Attendees <= 50 & DurationHours >= 2 ~ "Workshop",
TRUE ~ NA_character_))
myResultsTable <-
data_typed %>%
group_by(MeetingType) %>%
summarise(AttendeeMeetingHours = sum(Attendee_meeting_hours),
TotalMeetings = n()) %>%
mutate(Prop = AttendeeMeetingHours / sum(AttendeeMeetingHours)) %>%
mutate(Percent = paste(round(Prop * 100), "%"))
myResultsTableTotal <-
data_typed %>%
summarise(AttendeeMeetingHours = sum(Attendee_meeting_hours),
TotalMeetings = n()) %>%
mutate(Prop = AttendeeMeetingHours / sum(AttendeeMeetingHours),
Percent = paste(round(Prop * 100), "%"),
MeetingType = "Total") %>%
select(MeetingType, tidyselect::everything())
base_df <-
data.frame(id = 1:7,
value = c("All hands",
"Bloated",
"Status update",
"Decision making",
"One on one",
"Lengthy",
"Workshop"))
duration <-
c(0, 0, 3, 3,
0, 0, 2, 2,
0, 0, 1, 1,
0, 0, 1, 1,
0, 0, 1, 1,
1, 1, 2, 2,
2, 2, 3, 3)
attendees <-
c(4, 5, 5, 4,
3, 4, 4, 3,
2, 3, 3, 2,
1, 2, 2, 1,
0, 1, 1, 0,
0, 3, 3, 0,
0, 4, 4, 0)
main_plot_df <-
rbind(base_df,
base_df,
base_df,
base_df) %>%
arrange(id) %>%
mutate(Duration = duration,
Attendees = attendees)
label_df <-
main_plot_df %>%
group_by(id, value) %>%
summarise(x = mean(Duration),
y = mean(Attendees)) %>%
mutate(value2 = sub(" ", "\n", value),
text = ifelse(id %in% c(1, 2, 6, 7),"#FFFFFF", "black"),
fill = ifelse(id %in% c(1, 2, 6, 7),"#1d627e", "#34b1e2")) %>%
left_join(select(myResultsTable, MeetingType, Percent),
by = c("value" = "MeetingType")) %>%
mutate(Percent = ifelse(is.na(Percent), "0 %", Percent)) %>%
mutate(value2 = paste(value2, Percent, sep = "\n"))
colo_v <- setNames(label_df$fill, nm = base_df$value)
text_v <- setNames(label_df$text, nm = label_df$value)
plot_object <-
main_plot_df %>%
ggplot(aes(x = Duration, y = Attendees)) +
geom_polygon(aes(fill = value, group = id),
colour = "#FFFFFF") +
scale_fill_manual(values = colo_v) +
geom_text(data = label_df, aes(x = x, y = y, label = value2, colour = value), size = 3) +
scale_colour_manual(values = text_v) +
scale_x_continuous(breaks = 0:3,
labels = c("0", "1", "2+", "")) +
scale_y_continuous(breaks = 0:5,
labels = c("2", "3-8", "9-18",
"19-50", "51+", "")) +
labs(title = "Meeting types by attendees and duration",
subtitle = "% of total time spent in meetings",
ylab = "Attendees",
xlab = "Duration (hours)",
caption = paste("Data from week of",
myPeriod$Start,
"to week of",
myPeriod$End)) +
theme_wpa_basic() +
theme(legend.position = "none")
if(return == "table"){
rbind(myResultsTable,
myResultsTableTotal)
} else if(return == "plot"){
return(plot_object)
} else {
stop("Please enter a valid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/meetingtype_dist_mt.R
|
#' @title Create a summary bar chart of the proportion of Meeting Hours spent in
#' Long or Large Meetings
#'
#' @description
#' This function creates a bar chart showing the percentage of meeting hours
#' which are spent in long or large meetings.
#'
#' @param data Ways of Working Assessment query in the form of a data frame.
#' Requires the following variables:
#' - `Bloated_meeting_hours`
#' - `Lengthy_meeting_hours`
#' - `Workshop_meeting_hours`
#' - `All_hands_meeting_hours`
#' - `Status_update_meeting_hours`
#' - `Decision_making_meeting_hours`
#' - `One_on_one_meeting_hours`
#'
#' @param hrvar HR Variable by which to split metrics, defaults to
#' `"Organization"` but accepts any character vector, e.g.
#' `"LevelDesignation"`
#' @param mingroup Numeric value setting the privacy threshold / minimum group
#' size. Defaults to 5.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: ggplot object. A horizontal bar plot for the metric.
#' - `"table"`: data frame. A summary table for the metric.
#'
#' @import ggplot2
#' @import dplyr
#'
#' @family Visualization
#' @family Meetings
#'
#' @export
meetingtype_summary <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot"){
## Handling NULL values passed to hrvar
if(is.null(hrvar)){
data <- totals_col(data)
hrvar <- "Total"
}
mt_dist_str <- c("Bloated_meeting_hours",
"Lengthy_meeting_hours",
"Workshop_meeting_hours",
"All_hands_meeting_hours",
"Status_update_meeting_hours",
"Decision_making_meeting_hours",
"One_on_one_meeting_hours")
returnTable <-
data %>%
group_by(!!sym(hrvar)) %>%
summarise_at(vars(mt_dist_str), ~sum(., na.rm = TRUE)) %>%
gather(MeetingType, AttendeeMeetingHours, -!!sym(hrvar)) %>%
mutate(MeetingType = gsub(pattern = "_meeting_hours", replacement = "", x = MeetingType)) %>%
mutate(MeetingType = us_to_space(MeetingType)) %>%
group_by(!!sym(hrvar)) %>%
mutate(AttendeeMeetingHours = AttendeeMeetingHours / sum(AttendeeMeetingHours)) %>%
spread(MeetingType, AttendeeMeetingHours) %>%
left_join(hrvar_count(data, hrvar, return = "table"), by = hrvar) %>%
filter(n >= mingroup) %>%
ungroup() %>%
mutate(MeetingHoursInLongOrLargeMeetings = select(., c("All hands", "Bloated", "Lengthy", "Workshop")) %>%
apply(1, sum, na.rm = TRUE)) %>%
select(!!sym(hrvar), MeetingHoursInLongOrLargeMeetings, n)
if(return == "plot"){
returnTable %>%
create_bar_asis(group_var = hrvar,
bar_var = "MeetingHoursInLongOrLargeMeetings",
title = "% of Meeting Hours\nin Long or Large Meetings",
subtitle = paste0("By ", camel_clean(hrvar)),
caption = extract_date_range(data, return = "text"),
percent = TRUE,
bar_colour = "alert")
} else if(return == "table"){
returnTable
} else {
stop("Please enter a valid input for `return`.")
}
}
#' @rdname meetingtype_summary
#' @export
meetingtype_sum <- meetingtype_summary
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/meetingtype_summary.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Manager meeting coattendance distribution
#'
#' @description
#' Analyze degree of attendance between employes and their managers.
#' Returns a stacked bar plot of different buckets of coattendance.
#' Additional options available to return a table with distribution elements.
#'
#' @template spq-params
#'
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: ggplot object. A stacked bar plot showing the distribution of
#' manager co-attendance time.
#' - `"table"`: data frame. A summary table for manager co-attendance time.
#'
#' @import dplyr
#' @import ggplot2
#' @import reshape2
#' @import scales
#' @importFrom stats median
#' @importFrom stats sd
#'
#' @family Visualization
#' @family Managerial Relations
#'
#' @examples
#' # Return plot
#' mgrcoatt_dist(sq_data, hrvar = "Organization", return = "plot")
#'
#' # Return summary table
#' mgrcoatt_dist(sq_data, hrvar = "Organization", return = "table")
#'
#' @export
mgrcoatt_dist <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot") {
myPeriod <-
data %>%
mutate(Date=as.Date(Date, "%m/%d/%Y")) %>%
arrange(Date) %>%
mutate(Start=first(Date), End=last(Date)) %>%
filter(row_number()==1) %>%
select(Start, End)
## Basic Data for bar plot
plot_data <-
data %>%
rename(group = !!sym(hrvar)) %>%
group_by(PersonId) %>%
filter(Meeting_hours>0) %>%
mutate(coattendman_rate = Meeting_hours_with_manager / Meeting_hours) %>%
summarise(periods = n(),
group = first(group), coattendman_rate=mean(coattendman_rate)) %>%
group_by(group) %>%
mutate(Employee_Count = n_distinct(PersonId)) %>%
filter(Employee_Count >= mingroup)
## Create buckets of coattendance time
plot_data <-
plot_data %>%
mutate(bucket_coattendman_rate =
case_when(coattendman_rate>=0 & coattendman_rate<.25 ~ "0 - 25%",
coattendman_rate>=.25 & coattendman_rate<.5 ~ "25 - 50%",
coattendman_rate>=.50 & coattendman_rate<.75 ~ "50 - 75%",
coattendman_rate>=.75 ~ "75% +"))
## Employee count / base size table
plot_legend <-
plot_data %>%
group_by(group) %>%
summarize(Employee_Count=first(Employee_Count)) %>%
mutate(Employee_Count = paste("n=",Employee_Count))
## Data for bar plot
plot_table <-
plot_data %>%
group_by(group, bucket_coattendman_rate) %>%
summarize(Employees=n(),
Employee_Count=first(Employee_Count),
percent= Employees / Employee_Count) %>%
arrange(group, bucket_coattendman_rate)
## Table for annotation
annot_table <-
plot_legend %>%
dplyr::left_join(plot_table, by = "group")
## Remove max from axis labels, and add %
max_blank <- function(x){
as.character(
c(
scales::percent(
x[1:length(x) - 1]
),
"")
)
}
## Bar plot
plot_object <-
plot_table %>%
ggplot(aes(x = group, y=Employees, fill = bucket_coattendman_rate)) +
geom_bar(stat = "identity", position = position_fill(reverse = TRUE)) +
coord_flip() +
scale_y_continuous(expand = c(.01, 0), labels = max_blank, position = "right") +
annotate("text", x = plot_legend$group, y = 1.15, label = plot_legend$Employee_Count, size = 3) +
annotate("rect", xmin = 0.5, xmax = length(plot_legend$group) + 0.5, ymin = 1.05, ymax = 1.25, alpha = .2) +
annotate(x = length(plot_legend$group) + 0.8,
xend = length(plot_legend$group) + 0.8,
y = 0,
yend = 1,
colour = "black",
lwd = 0.75,
geom = "segment") +
scale_fill_manual(name="",
values = c("#bfe5ee", "#b4d5dd", "#fcf0eb", "#facebc")) +
theme_wpa_basic() +
theme(axis.line = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank()) +
labs(title = "Meetings coattended by line manager",
subtitle = paste("Percentage of meetings per person"),
caption = extract_date_range(data, return = "text"))
## Table to return
return_table <-
plot_table %>%
select(group, bucket_coattendman_rate, percent) %>%
spread(bucket_coattendman_rate, percent)
if(return == "table"){
return_table %>%
as_tibble() %>%
return()
} else if(return == "plot"){
return(plot_object)
} else {
stop("Please enter a valid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/mgrcoatt_dist.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Manager Relationship 2x2 Matrix
#'
#' @description
#' Generate the Manager-Relationship 2x2 matrix, returning a 'ggplot' object by
#' default. Additional options available to return a "wide" or "long" summary
#' table.
#'
#' @author Lucas Hogner <lucas.hogner@@microsoft.com>
#'
#' @param data Standard Person Query data to pass through. Accepts a data frame.
#' @param hrvar HR Variable by which to split metrics. Accepts a character
#' vector, e.g. "Organization". Defaults to `NULL`.
#' @param mingroup Numeric value setting the privacy threshold / minimum group
#' size. Defaults to 5.
#'
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#' - `"data"`
#'
#' See `Value` for more information.
#'
#' @param plot_colors Pass a character vector of length 4 containing HEX codes
#' to specify colors to use in plotting.
#' @param threshold
#' Specify a numeric value to determine threshold (in minutes) for 1:1 manager hours.
#' Defaults to 15.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: ggplot object. When `NULL` is passed to `hrvar`, a two-by-two
#' grid where the size of the grid represents total percentage of employees is
#' returned. Otherwise, a horizontal stacked bar plot is returned.
#' - `"table"`: data frame. A summary table is returned.
#' - `"data"`: data frame. A long table grouped at the `PersonId` level with
#' the following columns:
#' - `PersonId`
#' - HR variable supplied to `hrvar`
#' - `CoattendanceRate`
#' - `Meeting_hours_with_manager_1_on_1`
#' - `mgr1on1`
#' - `Type`
#'
#' @import dplyr
#' @import reshape2
#' @import ggplot2
#' @importFrom scales percent
#'
#' @family Visualization
#' @family Managerial Relations
#'
#' @examples
#' # Return matrix
#' mgrrel_matrix(sq_data)
#'
#' # Return stacked bar plot
#' mgrrel_matrix(sq_data, hrvar = "Organization")
#'
#' ## Visualize coaching style types
#' # Ensure dplyr is loaded
#' library(dplyr)
#'
#' # Extract PersonId and Coaching Type
#' match_df <-
#' sq_data %>%
#' mgrrel_matrix(return = "data") %>%
#' select(PersonId, Type)
#'
#' # Join and visualize baseline
#' sq_data %>%
#' left_join(match_df, by = "PersonId") %>%
#' keymetrics_scan(hrvar = "Type",
#' return = "plot")
#'
#' @export
mgrrel_matrix <- function(data,
hrvar = NULL,
mingroup = 5,
return = "plot",
plot_colors = c("#fe7f4f", "#b4d5dd", "#facebc", "#fcf0eb"),
threshold = 15){
## Add dummy "Total" column if hrvar = NULL
if(is.null(hrvar)){
data <- mutate(data, Total = "Total")
hrvar <- "Total"
}
## Check inputs
required_variables <- c("Date",
hrvar,
"PersonId",
"Meeting_hours_with_manager",
"Meeting_hours",
"Meeting_hours_with_manager_1_on_1")
## Error message if variables are not present
## Nothing happens if all present
data %>%
check_inputs(requirements = required_variables)
## Create a Person Weekly Average
data1 <-
data %>%
# Coattendance Rate with Manager
mutate(coattendman_rate =
(Meeting_hours_with_manager / Meeting_hours) %>%
tidyr::replace_na(replace = 0) %>% # Replace NAs with 0s
ifelse(!is.finite(.), 0, .)) %>% # Replace Inf with 0s
group_by(PersonId, !!sym(hrvar)) %>%
summarise(
Meeting_hours_with_manager = mean(Meeting_hours_with_manager, na.rm = TRUE),
Meeting_hours = mean(Meeting_hours, na.rm = TRUE),
Meeting_hours_with_manager_1_on_1 =
mean(Meeting_hours_with_manager_1_on_1, na.rm = TRUE),
coattendman_rate = mean(coattendman_rate, na.rm = TRUE),
Employee_Count = n_distinct(PersonId),
.groups = "drop"
)
## Threshold
thres_low_chr <- paste("<", threshold, "min")
thres_top_chr <- paste(">=", threshold, "min")
## Create key variables
data2 <-
data1 %>%
mutate(coattendande = ifelse(coattendman_rate < 0.5, "<50%", ">=50%"),
mgr1on1 = ifelse(Meeting_hours_with_manager_1_on_1 * 60 < threshold,
thres_low_chr,
thres_top_chr))
## Filter mingroup
valid_orgs <- NULL
valid_orgs <- # String with valid organizations
data2 %>%
hrvar_count(hrvar = hrvar,
return = "table") %>%
filter(n > mingroup) %>%
pull(!!sym(hrvar))
## Grouping variable split
if(hrvar == "Total"){
chart <-
data2 %>%
count(mgr1on1, coattendande) %>%
mutate(perc = n / sum(n)) %>% # Calculate percentages
mutate(xmin = ifelse(mgr1on1 == thres_low_chr, -sqrt(perc), 0),
xmax = ifelse(mgr1on1 == thres_top_chr, sqrt(perc), 0),
ymin = ifelse(coattendande == "<50%", -sqrt(perc), 0),
ymax = ifelse(coattendande == ">=50%", sqrt(perc), 0),
mgrRel = case_when(mgr1on1 == thres_low_chr & coattendande == "<50%" ~ "Under-coached",
mgr1on1 == thres_low_chr & coattendande == ">=50%" ~ "Co-attending",
mgr1on1 == thres_top_chr & coattendande == ">=50%" ~ "Highly managed",
TRUE ~ "Coaching")) %>%
mutate_at("mgrRel", ~as.factor(.))
clean_tb <-
chart %>%
select(mgrRel, n, perc) %>%
group_by(mgrRel) %>%
summarise_all(~sum(., na.rm = TRUE))
} else if(hrvar != "Total"){
chart <-
data2 %>%
count(!!sym(hrvar), mgr1on1, coattendande) %>%
group_by(!!sym(hrvar)) %>%
mutate(perc = n / sum(n)) %>% # Calculate percentages
mutate(xmin = ifelse(mgr1on1 == thres_low_chr, -sqrt(perc), 0),
xmax = ifelse(mgr1on1 == thres_top_chr, sqrt(perc), 0),
ymin = ifelse(coattendande == "<50%", -sqrt(perc), 0),
ymax = ifelse(coattendande == ">=50%", sqrt(perc), 0),
mgrRel = case_when(mgr1on1 == thres_low_chr & coattendande == "<50%" ~ "Under-coached",
mgr1on1 == thres_low_chr & coattendande == ">=50%" ~ "Co-attending",
mgr1on1 == thres_top_chr & coattendande == ">=50%" ~ "Highly managed",
TRUE ~ "Coaching")) %>%
ungroup() %>%
mutate_at("mgrRel", ~as.factor(.)) %>%
filter(!!sym(hrvar) %in% valid_orgs)
clean_tb <-
chart %>%
select(mgrRel, !!sym(hrvar), n, perc) %>%
group_by(mgrRel, !!sym(hrvar)) %>%
summarise_all(~sum(., na.rm = TRUE))
}
## Sort colours out
# Legacy variable names
myColors <- plot_colors
names(myColors) <- levels(chart$mgrRel)
## Show stacked bar chart if multiple groups
if(hrvar == "Total"){
plot <-
chart %>%
ggplot() +
geom_rect(aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, fill = mgrRel), color = "white") +
scale_fill_manual(name = "mgrRel", values = myColors) +
geom_text(aes(x = xmin + 0.5*sqrt(perc),
y = ymin + 0.5*sqrt(perc),
label = scales::percent(perc, accuracy = 1))) +
coord_equal() +
scale_x_continuous(breaks = c(-max(abs(chart$xmin),abs(chart$xmax))/2,max(abs(chart$xmin),abs(chart$xmax))/2),
labels = c(thres_low_chr, thres_top_chr),
limits = c(-max(abs(chart$xmin), abs(chart$xmax)), max(abs(chart$xmin), abs(chart$xmax)))) +
scale_y_continuous(breaks = c(-max(abs(chart$ymin), abs(chart$ymax))/2, max(abs(chart$ymin), abs(chart$ymax))/2),
labels = c("<50%", ">=50%"),
limits = c(-max(abs(chart$ymin), abs(chart$ymax)), max(abs(chart$ymin), abs(chart$ymax)))) +
theme_wpa_basic() +
labs(
x = "Weekly 1:1 time with manager",
y = "Employee and manager coattendance",
caption = extract_date_range(data, return = "text")
)
} else if(hrvar != "Total"){
plot <-
chart %>%
mutate(Fill = case_when(mgrRel == "Co-attending" ~ rgb2hex(68,151,169),
mgrRel == "Coaching" ~ rgb2hex(95,190,212),
mgrRel == "Highly managed" ~ rgb2hex(49,97,124),
mgrRel == "Under-coached" ~ rgb2hex(89,89,89))) %>%
ggplot(aes(x = !!sym(hrvar), y = perc, group = mgrRel, fill = Fill)) +
geom_bar(position = "stack", stat = "identity") +
geom_text(aes(label = paste(round(perc * 100), "%")),
position = position_stack(vjust = 0.5),
color = "#FFFFFF",
fontface = "bold") +
scale_fill_identity(name = "Coaching styles",
breaks = c(rgb2hex(68,151,169),
rgb2hex(95,190,212),
rgb2hex(49,97,124),
rgb2hex(89,89,89)),
labels = c("Co-attending",
"Coaching",
"Highly managed",
"Under-coached"),
guide = "legend") +
scale_y_continuous(labels = scales::percent) +
coord_flip() +
theme_wpa_basic() +
labs(title = "Distribution of types of \nmanager-direct relationship across organizations",
subtitle = "Based on manager 1:1 time and percentage of overall time spent with managers",
y = "Percentage")
}
if(return == "plot"){
plot +
labs(title = "Distribution of types of \nmanager-direct relationship",
subtitle = "Based on manager 1:1 time and percentage of\noverall time spent with managers")
} else if(return == "table"){
clean_tb %>%
as_tibble() %>%
return()
} else if(return == "chartdata"){
chart
} else if(return == "debug"){
data2
} else if(return == "data"){
data2 %>%
mutate(Type =
case_when(mgr1on1 == thres_low_chr & coattendande == "<50%" ~ "Under-coached",
mgr1on1 == thres_low_chr & coattendande == ">=50%" ~ "Co-attending",
mgr1on1 == thres_top_chr & coattendande == ">=50%" ~ "Highly managed",
TRUE ~ "Coaching")) %>%
select(PersonId,
!!sym(hrvar),
CoattendanceRate = "coattendman_rate",
Meeting_hours_with_manager_1_on_1,
mgr1on1,
Type)
} else {
stop("Please enter a valid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/mgrrel_matrix.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Sample Meeting Query dataset
#'
#' @description
#' A dataset generated from a Meeting Query from Workplace Analytics.
#'
#' @family Data
#'
#' @return data frame.
#'
#' @format A data frame with 2001 rows and 30 variables:
#' \describe{
#' \item{MeetingId}{ }
#' \item{StartDate}{ }
#' \item{StartTimeUTC}{ }
#' \item{EndDate}{ }
#' \item{EndTimeUTC}{ }
#' \item{Attendee_meeting_hours}{ }
#' \item{Attendees}{ }
#' \item{Organizer_Domain}{ }
#' \item{Organizer_FunctionType}{ }
#' \item{Organizer_LevelDesignation}{ }
#' \item{Organizer_Layer}{ }
#' \item{Organizer_Region}{ }
#' \item{Organizer_Organization}{ }
#' \item{Organizer_zId}{ }
#' \item{Organizer_attainment}{ }
#' \item{Organizer_TimeZone}{ }
#' \item{Organizer_HourlyRate}{ }
#' \item{Organizer_IsInternal}{ }
#' \item{Organizer_PersonId}{ }
#' \item{IsCancelled}{ }
#' \item{DurationHours}{ }
#' \item{IsRecurring}{ }
#' \item{Subject}{ }
#' \item{TotalAccept}{ }
#' \item{TotalNoResponse}{ }
#' \item{TotalDecline}{ }
#' \item{TotalNoEmailsDuringMeeting}{ }
#' \item{TotalNoDoubleBooked}{ }
#' \item{TotalNoAttendees}{ }
#' \item{MeetingResources}{ }
#' \item{Attendees_with_conflicting_meetings}{ }
#' \item{Invitees}{ }
#' \item{Emails_sent_during_meetings}{ }
#' \item{Attendees_multitasking}{ }
#' \item{Redundant_attendees}{ }
#' \item{Total_meeting_cost}{ }
#' \item{Total_redundant_hours}{ }
#'
#' ...
#' }
"mt_data"
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/mt_data.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title
#' Uncover HR attributes which best represent a population for a Person to
#' Person query
#'
#' @author Tannaz Sattari Tabrizi <Tannaz.Sattari@@microsoft.com>
#'
#' @description
#' `r lifecycle::badge('experimental')`
#'
#' Returns a data frame that gives a percentage of the group combinations that
#' best represent the population provided. Uses a person to person query. This
#' is used internally within `network_p2p()`.
#'
#' @param data Data frame containing a vertex table output from `network_p2p()`.
#' @param hrvar Character vector of length 3 containing the HR attributes to be
#' used. Defaults to `c("Organization", "LevelDesignation", "FunctionType")`.
#'
#' @import dplyr
#' @import tidyr
#'
#' @family Network
#'
#' @return data frame. A summary table giving the percentage of group
#' combinations that best represent the provided data.
#'
#' @examples
#' # Simulate a P2P edge list
#' sim_data <- p2p_data_sim()
#'
#' # Perform Louvain Community Detection and return vertices
#' lc_df <-
#' sim_data %>%
#' network_p2p(
#' community = "louvain",
#' return = "data"
#' )
#'
#' # Join org data from input edge list
#' joined_df <-
#' lc_df %>%
#' dplyr::left_join(
#' sim_data %>%
#' dplyr::select(TieOrigin_PersonId,
#' TieOrigin_Organization,
#' TieOrigin_LevelDesignation,
#' TieOrigin_City),
#' by = c("name" = "TieOrigin_PersonId"))
#'
#' # Describe cluster 2
#' joined_df %>%
#' # dplyr::filter(cluster == "2") %>%
#' network_describe(
#' hrvar = c(
#' "Organization",
#' "LevelDesignation",
#' "City"
#' )
#' ) %>%
#' dplyr::glimpse()
#'
#' @export
network_describe <- function(data,
hrvar = c("Organization",
"LevelDesignation",
"FunctionType")){
if(length(hrvar) != 3){
stop("Please provide a character vector of length 3 for `hrvar`")
}
## De-duplicated data containing only TieOrigins
filtered_Data <- unique(select(data, starts_with("TieOrigin_")))
## Select features
features <- select(filtered_Data, paste0("TieOrigin_", hrvar))
## Feature set: 1
max_percentages_1f <-
features %>%
colnames() %>%
purrr::map(function(c){
agg <-
features %>%
group_by_at(.vars = vars(c)) %>%
summarise(count = n(), .groups = "drop") %>%
# mutate(percentage = count / sum(count, na.rm = TRUE))
mutate(percentage = count)
agg %>%
arrange(desc(percentage)) %>%
mutate(feature_1 = c,
feature_1_value = !!sym(c)) %>%
select(feature_1, feature_1_value, Percentage = "percentage")
}) %>%
bind_rows()
## Feature set: 2
max_percentages_2f <-
list(c1 = colnames(features),
c2 = colnames(features)) %>%
expand.grid(stringsAsFactors = FALSE) %>%
filter(c1 != c2) %>%
purrr::pmap(function(c1, c2){
agg <-
features %>%
group_by_at(.vars=vars(c1, c2)) %>%
summarise(count = n(), .groups = "drop") %>%
# mutate(percentage = count / sum(count, na.rm = TRUE))
mutate(percentage = count)
agg %>%
arrange(desc(percentage)) %>%
mutate(feature_1 = c1,
feature_1_value = !!sym(as.character(c1)),
feature_2 = c2,
feature_2_value = !!sym(as.character(c2))) %>%
select(feature_1,
feature_1_value,
feature_2,
feature_2_value,
Percentage = "percentage")
}) %>%
bind_rows()
## Feature set: 3
max_percentages_3f <-
list(c1 = colnames(features),
c2 = colnames(features),
c3 = colnames(features)) %>%
expand.grid(stringsAsFactors = FALSE) %>%
filter(c1 != c2,
c2 != c3,
c3 != c1) %>%
purrr::pmap(function(c1, c2, c3){
agg <-
features %>%
group_by_at(.vars=vars(c1, c2, c3)) %>%
summarise(count = n(), .groups = "drop") %>%
# mutate(percentage = count / sum(count, na.rm = TRUE))
mutate(percentage = count)
agg %>%
arrange(desc(percentage)) %>%
mutate(feature_1 = c1,
feature_1_value = !!sym(c1),
feature_2 = c2,
feature_2_value = !!sym(c2),
feature_3 = c3,
feature_3_value = !!sym(c3)) %>%
select(feature_1,
feature_1_value,
feature_2,
feature_2_value,
feature_3,
feature_3_value,
Percentage = "percentage")
}) %>%
bind_rows()
list(max_percentages_1f,
max_percentages_2f,
max_percentages_3f) %>%
bind_rows() %>%
select(starts_with("feature"), Percentage) %>%
# Convert counts to percentage - description as % of community
mutate(Percentage = Percentage / nrow(filtered_Data))
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/network_describe.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Create a network plot with the group-to-group query
#'
#' @description
#' Pass a data frame containing a group-to-group query and return a network
#' plot. Automatically handles `"Collaborators_within_group"` and
#' `"Other_collaborators"` within query data.
#'
#' @param data Data frame containing a G2G query.
#' @param time_investor String containing the variable name for the Time
#' Investor column.
#' @param collaborator String containing the variable name for the Collaborator
#' column.
#' @param metric String containing the variable name for metric. Defaults to
#' `Collaboration_hours`.
#' @param algorithm String to specify the node placement algorithm to be used.
#' Defaults to `"fr"` for the force-directed algorithm of Fruchterman and
#' Reingold. See
#' <https://rdrr.io/cran/ggraph/man/layout_tbl_graph_igraph.html> for a full
#' list of options.
#' @param node_colour String or named vector to specify the colour to be used for displaying
#' nodes. Defaults to `"lightblue"`.
#' - If `"vary"` is supplied, a different colour is shown for each node at
#' random.
#' - If a named vector is supplied, the names must match the values of the
#' variable provided for the `time_investor` and `collaborator` columns. See
#' example section for details.
#' @param exc_threshold Numeric value between 0 and 1 specifying the exclusion
#' threshold to apply. Defaults to 0.1, which means that the plot will only
#' display collaboration above 10% of a node's total collaboration. This
#' argument has no impact on `"data"` or `"table"` return.
#' @param org_count Optional data frame to provide the size of each organization
#' in the `collaborator` attribute. The data frame should contain only two
#' columns:
#' - Name of the `collaborator` attribute excluding any prefixes, e.g.
#' `"Organization"`. Must be of character or factor type.
#' - `"n"`. Must be of numeric type.
#' Defaults to `NULL`, where node sizes will be fixed.
#'
#' @param subtitle String to override default plot subtitle.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#' - `"network"`
#' - `"data"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: 'ggplot' object. A group-to-group network plot.
#' - `"table"`: data frame. An interactive matrix of the network.
#' - `"network`: 'igraph' object used for creating the network plot.
#' - `"data"`: data frame. A long table of the underlying data.
#'
#' @import ggplot2
#' @import dplyr
#'
#' @family Network
#'
#' @examples
#' # Return a network plot
#' g2g_data %>% network_g2g()
#'
#' # Return a network plot - Meeting hours and 5% threshold
#' g2g_data %>%
#' network_g2g(time_investor = "TimeInvestors_Organization",
#' collaborator = "Collaborators_Organization",
#' metric = "Meeting_hours",
#' exc_threshold = 0.05)
#'
#' # Return a network plot - custom-specific colours
#' # Get labels of orgs and assign random colours
#' org_str <- unique(g2g_data$TimeInvestors_Organization)
#'
#' col_str <-
#' sample(
#' x = c("red", "green", "blue"),
#' size = length(org_str),
#' replace = TRUE
#' )
#'
#' # Create and supply a named vector to `node_colour`
#' names(col_str) <- org_str
#'
#' g2g_data %>%
#' network_g2g(node_colour = col_str)
#'
#'
#' # Return a network plot with circle layout
#' # Vary node colours and add org sizes
#' org_tb <- hrvar_count(
#' sq_data,
#' hrvar = "Organization",
#' return = "table"
#' )
#'
#' g2g_data %>%
#' network_g2g(algorithm = "circle",
#' node_colour = "vary",
#' org_count = org_tb)
#'
#' # Return an interaction matrix
#' # Minimum arguments specified
#' g2g_data %>%
#' network_g2g(return = "table")
#'
#'
#' @export
network_g2g <- function(data,
time_investor = NULL,
collaborator = NULL,
metric = "Collaboration_hours",
algorithm = "fr",
node_colour = "lightblue",
exc_threshold = 0.1,
org_count = NULL,
subtitle = "Collaboration Across Organizations",
return = "plot"){
if(is.null(time_investor)){
# Only return first match
time_investor <-
names(data)[grepl(pattern = "^TimeInvestors_", names(data))][1]
message(
paste("`time_investor` field not provided.",
"Assuming", wrap(time_investor, wrapper = "`"),
"as the `time_investor` variable.")
)
}
if(is.null(collaborator)){
# Only return first match
collaborator <-
names(data)[grepl(pattern = "^Collaborators_", names(data))][1]
message(
paste("`collaborator` field not provided.",
"Assuming", wrap(collaborator, wrapper = "`"),
"as the `collaborator` variable.")
)
}
## Get string of HR variable
hrvar_string <- gsub(pattern = "Collaborators_",
replacement = "",
x = collaborator)
## Warn if 'Collaborators Within Group' is not present in data
if(! "Collaborators Within Group" %in% unique(data[[collaborator]])){
warning(
"`Collaborators Within Group` is not found in the collaborator variable.
The analysis may be excluding in-group collaboration."
)
}
## Run plot_data
plot_data <-
data %>%
rename(TimeInvestorOrg = time_investor,
CollaboratorOrg = collaborator,
Metric = metric) %>%
mutate(CollaboratorOrg = case_when(CollaboratorOrg == "Collaborators Within Group" ~ TimeInvestorOrg,
TRUE ~ CollaboratorOrg)) %>%
group_by(TimeInvestorOrg, CollaboratorOrg) %>%
filter(TimeInvestorOrg != "Other_Collaborators" &
CollaboratorOrg!="Other_Collaborators") %>%
summarise_at("Metric", ~mean(.)) %>%
group_by(TimeInvestorOrg) %>%
mutate(metric_prop = Metric / sum(Metric, na.rm = TRUE)) %>%
select(TimeInvestorOrg, CollaboratorOrg, metric_prop) %>%
ungroup()
if(return == "table"){
## Return a 'tidy' matrix
plot_data %>%
tidyr::pivot_wider(names_from = CollaboratorOrg,
values_from = metric_prop)
} else if(return == "data"){
## Return long table
plot_data
} else if(return %in% c("plot", "network")){
## Network object
mynet_em <-
plot_data %>%
filter(metric_prop > exc_threshold) %>%
mutate_at(vars(TimeInvestorOrg, CollaboratorOrg), ~sub(pattern = " ", replacement = "\n", x = .)) %>%
mutate(metric_prop = metric_prop * 10) %>%
igraph::graph_from_data_frame(directed = FALSE)
# Org count vary by size -------------------------------------------
if(!is.null(org_count)){
igraph::V(mynet_em)$org_size <-
tibble(id = igraph::get.vertex.attribute(mynet_em)$name) %>%
mutate(id = gsub(pattern = "\n", replacement = " ", x = id)) %>%
left_join(org_count, by = c("id" = hrvar_string)) %>%
pull(n)
} else {
# Imputed size if not specified
igraph::V(mynet_em)$org_size <-
tibble(id = igraph::get.vertex.attribute(mynet_em)$name) %>%
mutate(id = gsub(pattern = "\n", replacement = " ", x = id)) %>%
mutate(n = 20) %>%
pull(n)
}
## Plot object
plot_obj <-
mynet_em %>%
ggraph::ggraph(layout = algorithm) +
ggraph::geom_edge_link(aes(edge_width = metric_prop * 1),
edge_alpha = 0.5,
edge_colour = "grey")
if(return == "network"){
mynet_em # Return 'igraph' object
} else {
# Custom node colours ----------------------------------------------
# String vector with length greater than 1
if(is.character(node_colour) & length(node_colour) > 1){
names(node_colour) <-
gsub(
pattern = " ",
replacement = "\n",
x = names(node_colour))
plot_obj <-
plot_obj +
ggraph::geom_node_point(
aes(color = name,
size = org_size),
alpha = 0.9
) +
scale_colour_manual(
# Enable matching
values = node_colour
)
# Auto assign colours
} else if(node_colour == "vary"){
plot_obj <-
plot_obj +
ggraph::geom_node_point(
aes(color = name,
size = org_size),
alpha = 0.9
)
} else {
plot_obj <-
plot_obj +
ggraph::geom_node_point(
aes(size = org_size),
colour = node_colour,
alpha = 0.9
)
}
plot_obj +
ggraph::geom_node_text(aes(label = name), size = 3, repel = FALSE) +
ggplot2::theme(
panel.background = ggplot2::element_rect(fill = 'white'),
legend.position = "none") +
theme_wpa_basic() +
scale_size(range = c(1, 30)) +
labs(title = "Group to Group Collaboration",
subtitle = subtitle,
x = "",
y = "",
caption = paste("Displays only collaboration above ", exc_threshold * 100, "% of node's total collaboration", sep = "")) +
theme(axis.line = element_blank(),
axis.text = element_blank(),
legend.position = "none")
}
} else {
stop("Please enter a valid input for `return`.")
}
}
#' @rdname network_g2g
#' @export
g2g_network <- network_g2g
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/network_g2g.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Perform network analysis with the person-to-person query
#'
#' @description
#' `r lifecycle::badge('experimental')`
#'
#' Analyse a person-to-person (P2P) network query, with multiple visualisation
#' and analysis output options. Pass a data frame containing a person-to-person
#' query and return a network visualization. Options are available for community
#' detection using either the Louvain or the Leiden algorithms.
#'
#' @param data Data frame containing a person-to-person query.
#' @param hrvar String containing the label for the HR attribute.
#' @param return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `'plot'` (default)
#' - `'plot-pdf'`
#' - `'sankey'`
#' - `'table'`
#' - `'data'`
#' - `'network'`
#' @param centrality string to determines which centrality measure is used to
#' scale the size of the nodes. All centrality measures are automatically
#' calculated when it is set to one of the below values, and reflected in the
#' `'network'` and `'data'` outputs.
#' Measures include:
#' - `betweenness`
#' - `closeness`
#' - `degree`
#' - `eigenvector`
#' - `pagerank`
#'
#' When `centrality` is set to NULL, no centrality is calculated in the outputs
#' and all the nodes would have the same size.
#'
#' @param community String determining which community detection algorithms to
#' apply. Valid values include:
#' - `NULL` (default): compute analysis or visuals without computing
#' communities.
#' - `"louvain"`
#' - `"leiden"`
#' - `"edge_betweenness"`
#' - `"fast_greedy"`
#' - `"fluid_communities"`
#' - `"infomap"`
#' - `"label_prop"`
#' - `"leading_eigen"`
#' - `"optimal"`
#' - `"spinglass"`
#' - `"walk_trap"`
#'
#' These values map to the community detection algorithms offered by `igraph`.
#' For instance, `"leiden"` is based on `igraph::cluster_leiden()`. Please see
#' the bottom of <https://igraph.org/r/html/1.3.0/cluster_leiden.html> on all
#' applications and parameters of these algorithms.
#' .
#' @param weight String to specify which column to use as weights for the
#' network. To create a graph without weights, supply `NULL` to this argument.
#' @param comm_args list containing the arguments to be passed through to
#' igraph's clustering algorithms. Arguments must be named. See examples
#' section on how to supply arguments in a named list.
#' @param layout String to specify the node placement algorithm to be used.
#' Defaults to `"mds"` for the deterministic multi-dimensional scaling of
#' nodes. See
#' <https://rdrr.io/cran/ggraph/man/layout_tbl_graph_igraph.html> for a full
#' list of options.
#' @param path File path for saving the PDF output. Defaults to a timestamped
#' path based on current parameters.
#' @param style String to specify which plotting style to use for the network
#' plot. Valid values include:
#' - `"igraph"`
#' - `"ggraph"`
#' @param bg_fill String to specify background fill colour.
#' @param font_col String to specify font colour.
#' @param legend_pos String to specify position of legend. Defaults to
#' `"right"`. See `ggplot2::theme()`. This is applicable for both the
#' 'ggraph' and the fast plotting method. Valid inputs include:
#' - `"bottom"`
#' - `"top"`
#' - `"left"`
#' -`"right"`
#'
#' @param palette String specifying the function to generate a colour palette
#' with a single argument `n`. Uses `"rainbow"` by default.
#' @param node_alpha A numeric value between 0 and 1 to specify the transparency
#' of the nodes. Defaults to 0.7.
#' @param edge_alpha A numeric value between 0 and 1 to specify the transparency
#' of the edges (only for 'ggraph' mode). Defaults to 1.
#' @param edge_col String to specify edge link colour.
#' @param node_sizes Numeric vector of length two to specify the range of node
#' sizes to rescale to, when `centrality` is set to a non-null value.
#' @param seed Seed for the random number generator passed to either
#' `set.seed()` when the louvain or leiden community detection algorithm is
#' used, to ensure consistency. Only applicable when `community` is set to
#' one of the valid non-null values.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `'plot'`: return a network plot, interactively within R.
#' - `'plot-pdf'`: save a network plot as PDF. This option is recommended when
#' the graph is large, which make take a long time to run if `return = 'plot'`
#' is selected. Use this together with `path` to control the save location.
#' - `'sankey'`: return a sankey plot combining communities and HR attribute.
#' This is only valid if a community detection method is selected at
#' `community`.
#' - `'table'`: return a vertex summary table with counts in communities and
#' HR attribute. When `centrality` is non-NULL, the average centrality values
#' are calculated per group.
#' - `'data'`: return a vertex data file that matches vertices with
#' communities and HR attributes.
#' - `'network'`: return 'igraph' object.
#'
#' @family Network
#'
#' @examples
#' p2p_df <- p2p_data_sim(dim = 1, size = 100)
#'
#' # default - ggraph visual
#' network_p2p(data = p2p_df, style = "ggraph")
#'
#' # return vertex table
#' network_p2p(data = p2p_df, return = "table")
#'
#' # return vertex table with community detection
#' network_p2p(data = p2p_df, community = "leiden", return = "table")
#'
#' # leiden - igraph style with custom resolution parameters
#' network_p2p(data = p2p_df, community = "leiden", comm_args = list("resolution" = 0.1))
#'
#' # louvain - ggraph style, using custom palette
#' network_p2p(
#' data = p2p_df,
#' style = "ggraph",
#' community = "louvain",
#' palette = "heat_colors"
#' )
#'
#' # leiden - return a sankey visual with custom resolution parameters
#' network_p2p(
#' data = p2p_df,
#' community = "leiden",
#' return = "sankey",
#' comm_args = list("resolution" = 0.1)
#' )
#'
#' # using `fluid_communities` algorithm with custom parameters
#' network_p2p(
#' data = p2p_df,
#' community = "fluid_communities",
#' comm_args = list("no.of.communities" = 5)
#' )
#'
#' # Calculate centrality measures and leiden communities, return at node level
#' network_p2p(
#' data = p2p_df,
#' centrality = "betweenness",
#' community = "leiden",
#' return = "data"
#' ) %>%
#' dplyr::glimpse()
#'
#' @import ggplot2
#' @import dplyr
#'
#' @export
network_p2p <-
function(
data,
hrvar = "Organization",
return = "plot",
centrality = NULL,
community = NULL,
weight = NULL,
comm_args = NULL,
layout = "mds",
path = paste("p2p", NULL, sep = "_"),
style = "igraph",
bg_fill = "#FFFFFF",
font_col = "grey20",
legend_pos = "right",
palette = "rainbow",
node_alpha = 0.7,
edge_alpha = 1,
edge_col = "#777777",
node_sizes = c(1, 20),
seed = 1
){
if(length(node_sizes) != 2){
stop("`node_sizes` must be of length 2")
}
## Set data frame for edges
if(is.null(weight)){
edges <-
data %>%
mutate(NoWeight = 1) %>% # No weight
select(from = "TieOrigin_PersonId",
to = "TieDestination_PersonId",
weight = "NoWeight")
} else {
edges <-
data %>%
select(from = "TieOrigin_PersonId",
to = "TieDestination_PersonId",
weight = weight)
}
## Set variables
# TieOrigin = PrimaryCollaborator
# TieDestination = SecondaryCollaborator
TO_hrvar <- paste0("TieOrigin_", hrvar)
TD_hrvar <- paste0("TieDestination_", hrvar)
## Vertices data frame to provide meta-data
vert_ft <-
rbind(
# TieOrigin
edges %>%
select(from) %>% # Single column
unique() %>% # Remove duplications
left_join(select(data, TieOrigin_PersonId, TO_hrvar),
by = c("from" = "TieOrigin_PersonId")) %>%
select(node = "from", !!sym(hrvar) := TO_hrvar),
# TieDestination
edges %>%
select(to) %>% # Single column
unique() %>% # Remove duplications
left_join(select(data, TieDestination_PersonId, TD_hrvar),
by = c("to" = "TieDestination_PersonId")) %>%
select(node = "to", !!sym(hrvar) := TD_hrvar)
)
## Create 'igraph' object
g_raw <-
igraph::graph_from_data_frame(edges,
directed = TRUE, # Directed, but FALSE for visualization
vertices = unique(vert_ft)) # remove duplicates
## Assign weights
g_raw$weight <- edges$weight
## allowed `community` values
valid_comm <- c(
"leiden",
"louvain",
"edge_betweenness",
"fast_greedy",
"fluid_communities",
"infomap",
"label_prop",
"leading_eigen",
"optimal",
"spinglass",
"walk_trap"
)
## Finalise `g` object
## If community detection is selected, this is where the communities are appended
if(is.null(community)){ # no community detection
g <- igraph::simplify(g_raw)
v_attr <- hrvar # Name of vertex attribute
} else if(community %in% valid_comm){
set.seed(seed = seed)
g_ud <- igraph::as.undirected(g_raw) # Convert to undirected
alg_label <- paste0("igraph::cluster_", community)
# combine arguments to clustering algorithm
c_comm_args <- c(list("graph" = g_ud), comm_args)
# output `communities` object
comm_out <- do.call(eval(parse(text = alg_label)), c_comm_args)
## Add cluster
g <-
g_ud %>%
# Add partitions to graph object
# Return membership
igraph::set_vertex_attr(
"cluster",
value = as.character(igraph::membership(comm_out))) %>%
igraph::simplify()
## Name of vertex attribute
v_attr <- "cluster"
} else {
stop("Please enter a valid input for `community`.")
}
# centrality calculations -------------------------------------------------
# attach centrality calculations if `centrality` is not NULL
if(!is.null(centrality)){
g <- network_summary(g, return = "network")
igraph::V(g)$node_size <-
igraph::get.vertex.attribute(
g,
name = centrality # from argument
) %>%
scales::rescale(to = node_sizes) # min and max value
} else {
# all nodes with the same size if centrality is not calculated
# adjust for plotting formats
if(style == "igraph"){
igraph::V(g)$node_size <- rep(3, igraph::vcount(g))
} else if(style == "ggraph"){
igraph::V(g)$node_size <- rep(2.5, igraph::vcount(g))
node_sizes <- c(3, 3) # arbitrarily fix the node size
}
}
# Common area -------------------------------------------------------------
## Create vertex table
vertex_tb <-
g %>%
igraph::get.vertex.attribute() %>%
as_tibble() %>%
select(-node_size) # never show `node_size` in data output
## Set layout for graph
g_layout <-
g %>%
ggraph::ggraph(layout = "igraph", algorithm = layout)
## Timestamped File Path
out_path <- paste0(path, "_", tstamp(), ".pdf")
# Return outputs ----------------------------------------------------------
## Use fast plotting method
if(return %in% c("plot", "plot-pdf")){
## Set colours
colour_tb <-
tibble(!!sym(v_attr) := unique(igraph::get.vertex.attribute(g, name = v_attr))) %>%
mutate(colour = eval(parse(text = paste0(palette,"(nrow(.))")))) # palette choice
## Colour vector
colour_v <-
tibble(!!sym(v_attr) := igraph::get.vertex.attribute(g, name = v_attr)) %>%
left_join(colour_tb, by = v_attr) %>%
pull(colour)
if(style == "igraph"){
# message("Using fast plot method due to large network size...")
## Set graph plot colours
igraph::V(g)$color <- grDevices::adjustcolor(colour_v, alpha.f = node_alpha)
igraph::V(g)$frame.color <- NA
igraph::E(g)$width <- 1
## Internal basic plotting function used inside `network_p2p()`
plot_basic_graph <- function(lpos = legend_pos){
old_par <- graphics::par(no.readonly = TRUE)
on.exit(graphics::par(old_par))
graphics::par(bg = bg_fill)
layout_text <- paste0("igraph::layout_with_", layout)
## Legend position
if(lpos == "left"){
leg_x <- -1.5
leg_y <- 0.5
} else if(lpos == "right"){
leg_x <- 1.5
leg_y <- 0.5
} else if(lpos == "top"){
leg_x <- 0
leg_y <- 1.5
} else if(lpos == "bottom"){
leg_x <- 0
leg_y <- -1.0
} else {
stop("Invalid `legend_pos` input.")
}
graphics::plot(
g,
layout = eval(parse(text = layout_text)),
vertex.label = NA,
# vertex.size = 3,
vertex.size = igraph::V(g)$node_size,
edge.arrow.mode = "-",
edge.color = "#adadad"
)
graphics::legend(x = leg_x,
y = leg_y,
legend = colour_tb[[v_attr]], # vertex attribute
pch = 21,
text.col = font_col,
col = edge_col,
pt.bg = colour_tb$colour,
pt.cex = 2,
cex = .8,
bty = "n",
ncol = 1)
}
## Default PDF output unless NULL supplied to path
if(return == "plot"){
plot_basic_graph()
} else if(return == "plot-pdf"){
grDevices::pdf(out_path)
plot_basic_graph()
grDevices::dev.off()
message(paste0("Saved to ", out_path, "."))
}
} else if(style == "ggraph"){
plot_output <-
g_layout +
ggraph::geom_edge_link(colour = edge_col,
edge_width = 0.05,
alpha = edge_alpha)+
ggraph::geom_node_point(aes(colour = !!sym(v_attr),
size = node_size),
alpha = node_alpha,
pch = 16) +
scale_size_continuous(range = node_sizes) +
scale_color_manual(values = unique(colour_v)) +
theme_void() +
theme(
legend.position = legend_pos,
legend.background = element_rect(fill = bg_fill, colour = bg_fill),
text = element_text(colour = font_col),
axis.line = element_blank(),
panel.grid = element_blank()
) +
labs(caption = paste0("Person to person collaboration showing ", v_attr, ". "), # spaces intentional
y = "",
x = "") +
guides(size = "none")
# Default PDF output unless NULL supplied to path
if(return == "plot"){
plot_output
} else if(return == "plot-pdf"){
ggsave(out_path,
plot = plot_output,
width = 16,
height = 9)
message(paste0("Saved to ", out_path, "."))
}
} else {
stop("invalid input for `style`")
}
} else if (return == "data"){
vertex_tb
} else if(return == "network"){
g
} else if(return == "sankey"){
if(is.null(community)){
message("Note: no sankey return option is available if `NULL` is selected at `community`.
Please specify a valid community detection algorithm.")
} else if(community %in% valid_comm){
create_sankey(
data = vertex_tb %>% count(!!sym(hrvar), cluster),
var1 = hrvar,
var2 = "cluster",
count = "n"
)
}
} else if(return == "table"){
if(is.null(community)){
if(is.null(centrality)){
vertex_tb %>% count(!!sym(hrvar))
} else {
# average centrality by group
vertex_tb %>%
group_by(!!sym(hrvar)) %>%
summarise(
n = n(),
betweenness = mean(betweenness, na.rm = TRUE),
closeness = mean(closeness, na.rm = TRUE),
degree = mean(degree, na.rm = TRUE),
eigenvector = mean(eigenvector, na.rm = TRUE),
pagerank = mean(pagerank, na.rm = TRUE)
)
}
} else if(community %in% valid_comm){
if(is.null(centrality)){
vertex_tb %>% count(!!sym(hrvar), cluster)
} else {
# average centrality by group
vertex_tb %>%
group_by(!!sym(hrvar), cluster) %>%
summarise(
n = n(),
betweenness = mean(betweenness, na.rm = TRUE),
closeness = mean(closeness, na.rm = TRUE),
degree = mean(degree, na.rm = TRUE),
eigenvector = mean(eigenvector, na.rm = TRUE),
pagerank = mean(pagerank, na.rm = TRUE)
)
}
}
} else {
stop("invalid input for `return`")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/network_p2p.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Summarise node centrality statistics with an igraph object
#'
#' @description
#' Pass an igraph object to the function and obtain centrality statistics for
#' each node in the object as a data frame. This function works as a wrapper of
#' the centralization functions in 'igraph'.
#'
#' @param graph 'igraph' object that can be returned from `network_g2g()` or
#' `network_p2p()`when the `return` argument is set to `"network"`.
#'
#' @param hrvar String containing the name of the HR Variable by which to split
#' metrics. Defaults to `NULL`.
#'
#' @param return String specifying what output to return. Valid inputs include:
#' - `"table"`
#' - `"network"`
#' - `"plot"`
#'
#' See `Value` for more information.
#'
#' @return
#' By default, a data frame containing centrality statistics. Available
#' statistics include:
#' - betweenness: number of shortest paths going through a node.
#' - closeness: number of steps required to access every other node from a
#' given node.
#' - degree: number of connections linked to a node.
#' - eigenvector: a measure of the influence a node has on a network.
#' - pagerank: calculates the PageRank for the specified vertices.
#' Please refer to the igraph package documentation for the detailed technical
#' definition.
#'
#' When `"network"` is passed to `"return"`, an 'igraph' object is returned with
#' additional node attributes containing centrality scores.
#'
#' When `"plot"` is passed to `"return"`, a summary table is returned showing
#' the average centrality scores by HR attribute. This is currently available if
#' there is a valid HR attribute.
#'
#' @family Network
#'
#' @examples
#' # Simulate a p2p network
#' p2p_data <- p2p_data_sim(size = 100)
#' g <- network_p2p(data = p2p_data, return = "network")
#'
#' # Return summary table
#' network_summary(graph = g, return = "table")
#'
#' # Return network with node centrality statistics
#' network_summary(graph = g, return = "network")
#'
#' # Return summary plot
#' network_summary(graph = g, return = "plot", hrvar = "Organization")
#'
#' # Simulate a g2g network and return table
#' g2 <- g2g_data %>% network_g2g(return = "network")
#' network_summary(graph = g2, return = "table")
#'
#' @export
network_summary <- function(graph, hrvar = NULL, return = "table"){
## NULL variables
node_id <- NULL
## Calculate summary table
sum_tb <-
dplyr::tibble(
node_id = igraph::vertex.attributes(graph = graph)$name,
betweenness = igraph::centralization.betweenness(graph = graph)$res,
closeness = igraph::centralization.closeness(graph = graph)$res,
degree = igraph::centralization.degree(graph = graph)$res,
eigenvector = igraph::centralization.evcent(graph = graph)$vector,
pagerank = igraph::page_rank(graph)$vector
)
if(!is.null(hrvar)){
sum_tb <-
cbind(
sum_tb,
hrvar = igraph::get.vertex.attribute(graph = graph, name = hrvar)
)
sum_tb <- dplyr::rename(sum_tb, !!sym(hrvar) := "hrvar")
}
if(return == "table"){
sum_tb
} else if(return == "network"){
graph <- igraph::set_vertex_attr(
graph = graph,
name = "betweenness",
value = sum_tb$betweenness
) %>%
igraph::set_vertex_attr(
name = "closeness",
value = sum_tb$closeness
) %>%
igraph::set_vertex_attr(
name = "degree",
value = sum_tb$degree
) %>%
igraph::set_vertex_attr(
name = "eigenvector",
value = sum_tb$eigenvector
) %>%
igraph::set_vertex_attr(
name = "pagerank",
value = sum_tb$pagerank
)
graph
} else if(return == "plot"){
if(is.null(hrvar)){
message("Visualisation options currently only available when a valid
HR attribute is supplied.")
} else {
plot_obj <-
sum_tb %>%
mutate(PersonId = node_id) %>%
mutate(Date = Sys.Date()) %>%
keymetrics_scan(
hrvar = hrvar,
metrics = c(
"betweenness",
"closeness",
"degree",
"eigenvector",
"pagerank"
)
)
}
plot_obj +
labs(
title = "Network centrality statistics",
subtitle = paste("By", hrvar),
caption = paste(
c(
"betweenness: number of shortest paths going through a node.",
"closeness: number of steps required to access every other node from a given node.",
"degree: number of connections linked to a node.",
"eigenvector: a measure of the influence a node has on a network.",
"pagerank: a measure of the relative importance of nodes based on linked nodes."
),
collapse = "\n"
)
)
} else {
stop("Invalid input to `return`")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/network_summary.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Distribution of Manager 1:1 Time as a 100% stacked bar
#'
#' @description
#' Analyze Manager 1:1 Time distribution.
#' Returns a stacked bar plot of different buckets of 1:1 time.
#' Additional options available to return a table with distribution elements.
#'
#' @inheritParams create_dist
#' @inherit create_dist return
#'
#' @family Visualization
#' @family Managerial Relations
#'
#' @examples
#' # Return plot
#' one2one_dist(sq_data, hrvar = "Organization", return = "plot")
#'
#' # Return summary table
#' one2one_dist(sq_data, hrvar = "Organization", return = "table")
#' @export
one2one_dist <- function(data,
hrvar = "Organization",
mingroup = 5,
dist_colours = c("#facebc",
"#fcf0eb",
"#b4d5dd",
"#bfe5ee"),
return = "plot",
cut = c(5, 15, 30)) {
cleaned_data <-
data %>%
mutate(`Scheduled 1:1 meeting minutes with manager` = Meeting_hours_with_manager_1_on_1 * 60)
create_dist(data = cleaned_data,
metric = "Scheduled 1:1 meeting minutes with manager",
hrvar = hrvar,
mingroup = mingroup,
dist_colours = dist_colours,
return = return,
cut = cut,
unit = "minutes")
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/one2one_dist.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Distribution of Manager 1:1 Time (Fizzy Drink plot)
#'
#' @description
#' Analyze weekly Manager 1:1 Time distribution, and returns
#' a 'fizzy' scatter plot by default.
#' Additional options available to return a table with distribution elements.
#'
#' @inheritParams create_fizz
#' @inherit create_fizz return
#'
#' @family Visualization
#' @family Managerial Relations
#'
#' @examples
#' # Return plot
#' one2one_fizz(sq_data, hrvar = "Organization", return = "plot")
#'
#' # Return a summary table
#' one2one_fizz(sq_data, hrvar = "Organization", return = "table")
#'
#' @export
one2one_fizz <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot"){
cleaned_data <-
data %>%
mutate(`Scheduled 1:1 meeting minutes with manager` = Meeting_hours_with_manager_1_on_1 * 60)
create_fizz(data = cleaned_data,
metric = "Scheduled 1:1 meeting minutes with manager",
hrvar = hrvar,
mingroup = mingroup,
return = return)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/one2one_fizz.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Frequency of Manager 1:1 Meetings as bar or 100% stacked bar chart
#'
#' @description `r lifecycle::badge('experimental')`
#'
#' This function calculates the average number of weeks (cadence) between of 1:1
#' meetings between an employee and their manager. Returns a distribution plot
#' for typical cadence of 1:1 meetings. Additional options available to return a
#' bar plot, tables, or a data frame with a cadence of 1 on 1 meetings metric.
#'
#' @template spq-params
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#' @param mode String specifying what method to use. This must be one of the
#' following strings:
#' - `"dist"`
#' - `"sum"`
#'
#' @inheritParams create_dist
#' @inherit create_dist return
#'
#' @section Distribution view:
#' For this view, there are four categories of cadence:
#' - Weekly (once per week)
#' - Twice monthly or more (up to 3 weeks)
#' - Monthly (3 - 6 weeks)
#' - Every two months (6 - 10 weeks)
#' - Quarterly or less (> 10 weeks)
#'
#' In the occasion there are zero 1:1 meetings with managers, this is included
#' into the last category, i.e. 'Quarterly or less'. Note that when `mode` is
#' set to `"sum"`, these rows are simply excluded from the calculation.
#'
#'
#' @family Visualization
#' @family Managerial Relations
#'
#' @examples
#' # Return plot, mode dist
#' one2one_freq(sq_data,
#' hrvar = "Organization",
#' return = "plot",
#' mode = "dist")
#'
#' # Return plot, mode sum
#' one2one_freq(sq_data,
#' hrvar = "Organization",
#' return = "plot",
#' mode = "sum")
#'
#' # Return summary table
#' one2one_freq(sq_data, hrvar = "Organization", return = "table")
#'
#' @export
one2one_freq <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot",
mode = "dist",
sort_by = "Quarterly or less\n(>10 weeks)") {
## Handling NULL values passed to hrvar
if(is.null(hrvar)){
data <- totals_col(data)
hrvar <- "Total"
}
expanded_data <-
data %>%
mutate(
Meetings_with_manager_1_on_1 = Meetings_with_manager_1_on_1 > 0
) %>%
group_by(PersonId) %>%
mutate(
Cadence_of_1_on_1_meetings_with_manager =
1 / (sum(Meetings_with_manager_1_on_1) / n())
)
# Arbitrarily large constant -----------------------------------------------
arb_const <- 99999
# `breaks_to_labels()` -----------------------------------------------------
breaks_to_labels <- function(x){
lookup <-
c(
"Weekly\n(once per week)" = "< 1 Weeks",
"Twice monthly or more\n(up to 3 weeks)" = "1 - 3 Weeks",
"Monthly\n(3 - 6 weeks)" = "3 - 6 Weeks",
"Every two months\n(6 - 10 weeks)" = "6 - 10 Weeks",
"Quarterly or less\n(>10 weeks)" = "10+ Weeks"
)
ifelse(
is.na(names(lookup[match(x, lookup)])),
x,
names(lookup[match(x, lookup)])
)
}
# Return outputs -----------------------------------------------------------
if(return == "data"){
expanded_data
}
else if(mode == "sum" & return == "plot"){
expanded_data %>%
filter_all(all_vars(!is.infinite(.))) %>%
create_bar(
metric = "Cadence_of_1_on_1_meetings_with_manager",
hrvar = hrvar,
return = "table",
mingroup = mingroup) %>%
ggplot(aes(x = Cadence_of_1_on_1_meetings_with_manager, y = group)) +
geom_point(colour = "#FE7F4F") +
scale_x_continuous("Manager 1:1 - Frequency in Weeks") +
labs(
title = "Cadence of 1:1 Meetings with manager",
subtitle = paste("Averages values, by ", hrvar),
caption = paste(
"Excludes individuals with no 1:1 meetings. ",
extract_date_range(data, return = "text")
),
x = camel_clean(hrvar)
) +
theme_wpa_basic() +
scale_size(guide = "none", range = c(1, 15)) +
theme(
axis.line = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.major.y = element_line(colour = "#D9E7F7", size = 3),
# lightblue bar
panel.grid.minor.x = element_line(color = "gray"),
strip.placement = "outside",
strip.background = element_blank(),
strip.text = element_blank(
)
)
} else if(mode == "sum" & return == "table"){
expanded_data %>%
filter_all(all_vars(!is.infinite(.))) %>%
create_bar(
metric = "Cadence_of_1_on_1_meetings_with_manager",
hrvar = hrvar,
return = "table",
mingroup = mingroup
)
} else if(mode == "dist"){
plot_data <-
expanded_data %>%
mutate(
across(
.cols = Cadence_of_1_on_1_meetings_with_manager,
.fns = ~ifelse(!is.finite(.), arb_const, .)
)
)
create_dist(
plot_data,
metric = "Cadence_of_1_on_1_meetings_with_manager",
hrvar = hrvar,
mingroup = mingroup,
cut = c(
1, # Once a week
3, # Twice monthly or more
6, # Monthly
10 # Bi-monthly
),
ubound = arb_const + 1, # Bigger than arbitrary constant
dist_colours = c(
"#F1B8A1", # Reddish orange
"#facebc", # Orangeish
"#fcf0eb", # Light orange
# "grey90", # Light grey
"#bfe5ee", # Light teal
"#b4d5dd" # Dark teal
),
unit = "Weeks",
labels = breaks_to_labels,
return = return,
sort_by = sort_by
)
} else {
stop("Invalid value passed to `mode` or `return`")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/one2one_freq.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Manager 1:1 Time Trend - Line Chart
#'
#' @description
#' Provides a week by week view of 1:1 time with managers, visualised as line charts.
#' By default returns a line chart for 1:1 meeting hours,
#' with a separate panel per value in the HR attribute.
#' Additional options available to return a summary table.
#'
#' @details
#' Uses the metric `Meeting_hours_with_manager_1_on_1`.
#'
#' @inheritParams create_line
#' @inherit create_line return
#'
#' @family Visualization
#' @family Managerial Relations
#'
#' @examples
#' # Return a line plot
#' one2one_line(sq_data, hrvar = "LevelDesignation")
#'
#' # Return summary table
#' one2one_line(sq_data, hrvar = "LevelDesignation", return = "table")
#'
#' @export
one2one_line <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot"){
## Inherit arguments
create_line(data = data,
metric = "Meeting_hours_with_manager_1_on_1",
hrvar = hrvar,
mingroup = mingroup,
return = return)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/one2one_line.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Manager 1:1 Time Ranking
#'
#' @description
#' This function scans a standard query output for groups with high levels of
#' 'Manager 1:1 Time'. Returns a plot by default, with an option to return a
#' table with a all of groups (across multiple HR attributes) ranked by manager
#' 1:1 time.
#'
#' @details
#' Uses the metric `Meeting_hours_with_manager_1_on_1`.
#' See `create_rank()` for applying the same analysis to a different metric.
#'
#' @inheritParams create_rank
#' @inherit create_rank return
#'
#' @family Visualization
#' @family Managerial Relations
#'
#' @examples
#' # Return rank table
#' one2one_rank(
#' data = sq_data,
#' return = "table"
#' )
#'
#' # Return plot
#' one2one_rank(
#' data = sq_data,
#' return = "plot"
#' )
#'
#' @export
one2one_rank <- function(data,
hrvar = extract_hr(data),
mingroup = 5,
mode = "simple",
plot_mode = 1,
return = "plot"){
data %>%
create_rank(metric = "Meeting_hours_with_manager_1_on_1",
hrvar = hrvar,
mingroup = mingroup,
mode = mode,
plot_mode = plot_mode,
return = return)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/one2one_rank.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Manager 1:1 Time Summary
#'
#' @description
#' Provides an overview analysis of Manager 1:1 Time. Returns a bar plot showing
#' average weekly minutes of Manager 1:1 Time by default. Additional options
#' available to return a summary table.
#'
#' @inheritParams create_bar
#' @inherit create_bar return
#'
#' @family Visualization
#' @family Managerial Relations
#'
#' @examples
#' # Return a ggplot bar chart
#' one2one_sum(sq_data, hrvar = "LevelDesignation")
#'
#' # Return a summary table
#' one2one_sum(sq_data, hrvar = "LevelDesignation", return = "table")
#'
#' @export
one2one_sum <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot"){
cleaned_data <-
data %>%
mutate(`Scheduled 1:1 meeting minutes with manager` = Meeting_hours_with_manager_1_on_1 * 60)
create_bar(data = cleaned_data,
hrvar = hrvar,
mingroup = mingroup,
metric = "Scheduled 1:1 meeting minutes with manager",
return = return,
bar_colour = "darkblue")
}
#' @rdname one2one_sum
#' @export
one2one_summary <- one2one_sum
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/one2one_sum.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Manager 1:1 Time Trend
#'
#' @description
#' Provides a week by week view of scheduled manager 1:1 Time. By default
#' returns a week by week heatmap, highlighting the points in time with most
#' activity. Additional options available to return a summary table.
#'
#' @details
#' Uses the metric `Meeting_hours_with_manager_1_on_1`.
#'
#' @inheritParams create_trend
#' @inherit create_trend return
#'
#' @family Visualization
#' @family Managerial Relations
#'
#'
#' @export
one2one_trend <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot"){
create_trend(data,
metric = "Meeting_hours_with_manager_1_on_1",
hrvar = hrvar,
mingroup = mingroup,
return = return)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/one2one_trend.R
|
#' @title Simulate a person-to-person query using a Watts-Strogatz model
#'
#' @description Generate an person-to-person query / edgelist based on the graph
#' according to the Watts-Strogatz small-world network model. Organizational
#' data fields are also simulated for `Organization`, `LevelDesignation`, and
#' `City`.
#'
#' @param dim Integer constant, the dimension of the starting lattice.
#' @param size Integer constant, the size of the lattice along each dimension.
#' @param nei Integer constant, the neighborhood within which the vertices of
#' the lattice will be connected.
#' @param p Real constant between zero and one, the rewiring probability.
#'
#' @details
#' This is a wrapper around `igraph::watts.strogatz.game()`. See igraph
#' documentation for details on methodology. Loop edges and multiple edges are
#' disabled. Size of the network can be changing the arguments `size` and `nei`.
#'
#' @examples
#' # Simulate a p2p dataset with 800 edges
#' p2p_data_sim(size = 200, nei = 4)
#'
#' @return
#' data frame with the same column structure as a person-to-person flexible
#' query. This has an edgelist structure and can be used directly as an input
#' to `network_p2p()`.
#'
#' @family Data
#' @family Network
#'
#' @export
p2p_data_sim <- function(dim = 1,
size = 300,
nei = 5,
p = 0.05){
igraph::watts.strogatz.game(dim = dim,
size = size,
nei = nei,
p = p) %>%
igraph::as_edgelist() %>%
as.data.frame() %>%
dplyr::rename(TieOrigin_PersonId = "V1",
TieDestination_PersonId = "V2") %>%
dplyr::mutate(TieOrigin_Organization = add_cat(TieOrigin_PersonId, "Organization"),
TieDestination_Organization = add_cat(TieDestination_PersonId, "Organization"),
TieOrigin_LevelDesignation = add_cat(TieOrigin_PersonId, "LevelDesignation"),
TieDestination_LevelDesignation = add_cat(TieDestination_PersonId, "LevelDesignation"),
TieOrigin_City = add_cat(TieOrigin_PersonId, "City"),
TieDestination_City = add_cat(TieDestination_PersonId, "City")) %>%
dplyr::mutate_at(dplyr::vars(dplyr::ends_with("PersonId")),
~paste0("SIM_ID_", .)) %>%
dplyr::mutate(StrongTieScore = 1)
}
#' Add organizational data to the simulated p2p data
#' @param x Numeric vector to be assigned simulated organizational attributes
#' @param type String with three valid options:
#' - `Organization`
#' - `LevelDesignation`
#' - `City`
#'
#' @noRd
add_cat <- function(x, type){
if(type == "Organization"){
dplyr::case_when((x %% 7 == 0) ~ "Org A",
(x %% 6 == 0) ~ "Org B",
(x %% 5 == 0) ~ "Org C",
(x %% 4 == 0) ~ "Org D",
(x %% 3 == 0) ~ "Org E",
x < 100 ~ "Org F",
(x %% 2 == 0) ~ "Org G", # Even number
TRUE ~ "Org H")
} else if(type == "LevelDesignation"){
paste("Level", substr(x, 1, 1)) # Extract first digit
} else if(type == "City"){
dplyr::case_when((x %% 3 == 0) ~ "City A", # Divisible by 3
(x %% 2 == 0) ~ "City B",
TRUE ~ "City C")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/p2p_data_sim.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title
#' Calculate the p-value of the null hypothesis that two outcomes are from the
#' same dataset
#'
#' @description
#' Specify an outcome variable and return p-test outputs.
#' All numeric variables in the dataset are used as predictor variables.
#'
#' @author Mark Powers <mark.powers@@microsoft.com>
#'
#' @param data A Person Query dataset in the form of a data frame.
#' @param outcome A string specifying the name of a binary variable, i.e. can
#' only contain the values 1 or 0. Used to group the two distributions.
#' @param behavior A character vector specifying the column to be used as the
#' behavior to test.
#' @param paired Specify whether the dataset is paired or not. Defaults to
#' `TRUE`.
#'
#' @return
#' Returns a numeric value representing the p-value outcome of the test.
#'
#' @family Support
#'
#' @import dplyr
#'
#' @details
#' This function is a wrapper around `wilcox.test()` from 'stats'.
#'
#' @examples
#' # Simulate a binary variable X
#' # Returns a single p-value
#' library(dplyr)
#' sq_data %>%
#' mutate(X = ifelse(Email_hours > 6, 1, 0)) %>%
#' p_test(outcome = "X", behavior = "External_network_size")
#'
#' @export
p_test <- function(data,
outcome,
behavior,
paired = FALSE){
train <- data %>%
dplyr::filter(!!sym(outcome) == 1 | !!sym(outcome) == 0) %>%
select(!!sym(outcome), !!sym(behavior)) %>%
mutate(outcome = as.character(!!sym(outcome))) %>%
mutate(outcome = as.factor(!!sym(outcome)))
pos <- train %>% dplyr::filter(outcome == 1, na.rm=TRUE) %>% select(behavior)
neg <- train %>% dplyr::filter(outcome == 0, na.rm=TRUE) %>% select(behavior)
s <- stats::wilcox.test(unlist(pos), unlist(neg), paired = paired)
return(s$p.value)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/p_test.R
|
#' @title Perform a pairwise count of words by id
#'
#' @description This is a 'data.table' implementation that mimics the output of
#' `pairwise_count()` from 'widyr' to reduce package dependency. This is used
#' internally within `tm_cooc()`.
#'
#' @param data Data frame output from `tm_clean()`.
#' @param id String to represent the id variable. Defaults to `"line"`.
#' @param word String to represent the word variable. Defaults to `"word"`.
#'
#' @return
#' data frame with the following columns representing a pairwise count:
#' - `"item1"`
#' - `"item2"`
#' - `"n"`
#'
#' @importFrom data.table ":=" "%like%" "%between%" rbindlist as.data.table
#'
#' @family Support
#' @family Text-mining
#'
#' @examples
#' td <- data.frame(line = c(1, 1, 2, 2),
#' word = c("work", "meeting", "catch", "up"))
#'
#' pairwise_count(td, id = "line", word = "word")
#'
#' @export
pairwise_count <- function(data,
id = "line",
word = "word"){
# Make sure data.table knows we know we're using it
.datatable.aware = TRUE
data <-
data %>%
dplyr::rename(word := !!sym(word),
id := !!sym(id))
DT <- data.table::as.data.table(data)
# convert to character
DT[, word := as.character(word)]
# subset those with >1 per id
DT2 <- DT[, N := .N, by = id][N>1]
# create all combinations of 2
# return as a data.table with these as columns `V1` and `V2`
# then count the numbers in each id
out_data <-
DT2[, rbindlist(utils::combn(word,2,
FUN = function(x) as.data.table(as.list(x)),
simplify = FALSE)), by = id] %>%
.[, .N, by = list(V1,V2)]
# format and sort
out_data %>%
dplyr::as_tibble() %>%
dplyr::rename(item1 = "V1",
item2 = "V2",
n = "N") %>%
dplyr::arrange(desc(n))
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/pairwise_count.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Plot the distribution of percentage change between periods
#' of a Viva Insights metric by the number of employees.
#'
#' @description
#' This function also presents the p-value for the null hypothesis
#' that the variable has not changed, using a Wilcox signed-rank test.
#'
#' @author Mark Powers <mark.powers@@microsoft.com>
#'
#' @param data Person Query as a dataframe including date column named `"Date"`
#' This function assumes the data format is `MM/DD/YYYY` as is standard in a
#' Viva Insights query output.
#' @param compvar comparison variable to compare person change before and
#' after For example, `"Collaboration_hours"`
#' @param before_start Start date of "before" time period in `YYYY-MM-DD`
#' @param before_end End date of "before" time period in `YYYY-MM-DD`
#' @param after_start Start date of "after" time period in `YYYY-MM-DD`
#' @param after_end End date of "after" time period in `YYYY-MM-DD`
#' @param return Character vector specifying whether to return plot as Count or
#' Percentage of Employees. Valid inputs include:
#' - `"count"` (default)
#' - `"percentage"`
#' - `"table"`
#'
#' @return
#' ggplot object showing a bar plot (histogram) of change for two time
#' intervals.
#'
#' @import dplyr
#' @import reshape2
#' @import ggplot2
#' @import scales
#' @importFrom stats wilcox.test
#'
#' @family Visualization
#' @family Time-series
#' @family Flexible
#'
#' @examples
#' # Run plot
#' period_change(sq_data, compvar = "Workweek_span", before_end = "2019-12-29")
#'
#' \donttest{
#' # Run plot with more specific arguments
#' period_change(sq_data,
#' compvar = "Workweek_span",
#' before_start = "2019-12-15",
#' before_end = "2019-12-29",
#' after_start = "2020-01-05",
#' after_end = "2020-01-26",
#' return = "percentage")
#' }
#' @family Flexible Input
#' @export
period_change <-
function(data,
compvar,
before_start = min(as.Date(data$Date, "%m/%d/%Y")),
before_end,
after_start = as.Date(before_end) + 1,
after_end = max(as.Date(data$Date, "%m/%d/%Y")),
return = "count") {
## Check inputs
## Update these column names as per appropriate
required_variables <- c("Date",
compvar,
"PersonId")
## Error message if variables are not present
## Nothing happens if all present
data %>%
check_inputs(requirements = required_variables)
daterange_1_start <- as.Date(before_start)
daterange_1_end <- as.Date(before_end)
daterange_2_start <- as.Date(after_start)
daterange_2_end <- as.Date(after_end)
# Fix dates format for Workplace Analytics Queries
WpA_dataset <- data %>% mutate(Date = as.Date(Date, "%m/%d/%Y"))
# Check for dates in data file
if (daterange_1_start < min(WpA_dataset$Date) |
daterange_1_start > max(WpA_dataset$Date) |
daterange_1_end < min(WpA_dataset$Date) |
daterange_1_end > max(WpA_dataset$Date) |
daterange_2_start < min(WpA_dataset$Date) |
daterange_2_start > max(WpA_dataset$Date) |
daterange_2_end < min(WpA_dataset$Date) |
daterange_2_end > max(WpA_dataset$Date)) {
stop('Dates not found in dataset')
geterrmessage()
}
# Create variable => Period
WpA_dataset_table <-
WpA_dataset %>% mutate(
Period = case_when(
Date >= daterange_1_start &
Date <= daterange_1_end ~ "Before",
Date >= daterange_2_start &
Date <= daterange_2_end ~ "After"
)
) %>% filter(Period == "Before" | Period == "After")
# Group data by
mydata_table <-
WpA_dataset_table %>%
group_by(Period, PersonId) %>%
summarise_if(is.numeric, mean, na.rm = TRUE)
# Select comparison variable
mydata_table <-
mydata_table %>% select(PersonId, Period, all_of(compvar))
# Turn to Long
data_wide <- tidyr::gather(mydata_table, KPI, value,-Period,-PersonId)
# Turn to Wide
data_final <- tidyr::spread(data_wide, Period, value)
# Drop nas
data_final <- data_final %>% tidyr::drop_na()
# run Wilcox Signed-Rank test
test_set <- data_final
res <- wilcox.test(test_set$Before, test_set$After, paired = TRUE)
p_val <- signif(res$p.value, digits = 3)
# Calculate change between periods
data_final <- data_final %>% mutate(delta = After - Before)
# Calculate percent change between periods
data_final <-
data_final %>% mutate(perc_diff = (After - Before) / Before)
# Drop NA and Errors
data_final <- data_final %>% tidyr::drop_na(delta)
data_final <-
data_final %>% filter(Before > 0) #filters out people who joined the organization after the 'Before' period
# Group 100%+ together so you can see how many are over 100% in a plot data set
data_plot <- data_final
data_plot$perc_diff[which(data_plot$perc_diff > 1)] <- 1.01
# Categorize perc_diff by percentages
data_plot <-
data_plot %>% mutate(Mybins = cut_width(
perc_diff,
width = 0.1,
boundary = 0,
labels = F
))
# create x-axis labels and replace Mybins with label
labels = c(paste(seq(-100, 100, 10), "%", sep = ""), "100%+")
x_axis <- vector("character", 21)
for (i in 1:20) {
x_axis[i] <- paste(labels[i], "-", labels[i + 1])
}
x_axis[21] <- labels[21]
data_plot <- data_plot %>% mutate(Mybins = x_axis[Mybins])
data_plot <-
data_plot %>%
mutate(Mybins = factor(Mybins, levels = x_axis))
#calculate percentage of employees in each bin
data_legend <-
data_plot %>%
group_by(Mybins) %>%
summarize(Employee_Count = n_distinct(PersonId))
data_legend <- data.frame(data_legend)
data_legend <-
data_legend %>%
mutate(Employee_Counts = paste("n=", Employee_Count))
data_legend <-
data_legend %>%
mutate(Employee_perc = Employee_Count / sum(data_legend$Employee_Count))
# create summary table for table output
summary_table <-
data_legend %>%
select(Mybins, Employee_Count, Employee_perc)
if (return == "count") {
# Plot barplot of Count of Employees with % change
data_plot %>%
ggplot(aes(x = Mybins)) +
geom_bar(fill = "#203864") +
scale_x_discrete(name = "Percent change") +
scale_y_continuous(name = "Employee count") +
theme_wpa_basic() +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
labs(
title = paste("Number of employees with change in", compvar),
subtitle = paste(
"Period 1:",
daterange_1_start,
"to",
daterange_1_end,
"and Period 2:",
daterange_2_start,
"to",
daterange_2_end
)
) +
labs(
caption = paste(
"Total employees =",
sum(data_legend$Employee_Count),
"| Data from",
daterange_1_start,
"to",
daterange_1_end,
"and",
daterange_2_start,
"to",
daterange_2_end,
"| p =",
p_val
)
)
} else if (return == "percentage") {
# Create histogram by % of employees changing
data_legend %>%
ggplot(aes(x = Mybins, y = Employee_perc)) +
geom_col( fill = "#203864") +
scale_x_discrete(name = "Percent change") +
scale_y_continuous(name = "Percentage of measured employees",
labels = scales::percent_format(accuracy = 1)) +
annotate(
"text",
x = data_legend$Mybins,
y = -0.005,
label = data_legend$Employee_Counts,
size = 3
) +
theme_wpa_basic() +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
labs(
title = paste("Percentage of employees with change in", compvar),
subtitle = paste(
"Period 1:",
daterange_1_start,
"to",
daterange_1_end,
"and Period 2:",
daterange_2_start,
"to",
daterange_2_end
)
) +
labs(
caption = paste(
"Total employees =",
sum(data_legend$Employee_Count),
"| Data from",
daterange_1_start,
"to",
daterange_1_end,
"and",
daterange_2_start,
"to",
daterange_2_end,
"| p =",
p_val
)
)
} else if(return == "table"){
summary_table %>%
mutate_at("Employee_perc", ~round(. * 100, 1)) %>%
as_tibble() %>%
return()
} else {
stop("Please enter a valid input for `return`, either count, percentage, or table.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/period_change.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Create hierarchical clusters of selected metrics using a Person query
#'
#' @description
#' `r lifecycle::badge('questioning')`
#'
#' Apply hierarchical clustering to selected metrics. Person averages are computed prior to clustering.
#' The hierarchical clustering uses cosine distance and the ward.D method
#' of agglomeration.
#'
#' @author Ainize Cidoncha <ainize.cidoncha@@microsoft.com>
#'
#' @param data A data frame containing `PersonId` and selected metrics for
#' clustering.
#' @param metrics Character vector containing names of metrics to use for
#' clustering. See examples section.
#' @param k Numeric vector to specify the `k` number of clusters to cut by.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"data"`
#' - `"table"`
#' - `"hclust"`
#'
#' See `Value` for more information.
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: 'ggplot' object. A heatmap plot comparing the key metric averages
#' of the clusters as per `keymetrics_scan()`.
#' - `"data"`: data frame. Raw data with clusters appended
#' - `"table"`: data frame. Summary table for identified clusters
#' - `"hclust"`: 'hclust' object. hierarchical model generated by the function.
#'
#' @import dplyr
#' @import tidyselect
#' @import ggplot2
#' @importFrom proxy dist
#' @importFrom stats hclust
#' @importFrom stats rect.hclust
#' @importFrom stats cutree
#' @importFrom tidyr replace_na
#'
#' @family Clustering
#'
#' @examples
#' \donttest{
#' # Return plot
#' personas_hclust(sq_data,
#' metrics = c("Collaboration_hours", "Workweek_span"),
#' k = 4)
#'
#' # Return summary table
#'
#' personas_hclust(sq_data,
#' metrics = c("Collaboration_hours", "Workweek_span"),
#' k = 4,
#' return = "table")
#'
#' # Return data with clusters appended
#' personas_hclust(sq_data,
#' metrics = c("Collaboration_hours", "Workweek_span"),
#' k = 4,
#' return = "data")
#' }
#'
#' @export
personas_hclust <- function(data,
metrics,
k = 4,
return = "plot"){
## Use names for matching
input_var <- metrics
## transform the data for clusters
data_cluster <-
data %>%
select(PersonId, input_var) %>%
group_by(PersonId) %>%
summarise_at(vars(input_var), ~mean(., na.rm = TRUE), .groups = "drop")
## Run hclust
h_clust <-
data_cluster %>%
select(input_var) %>%
proxy::dist(method = "cosine") %>%
stats::hclust(method = "ward.D")
## Cut tree
cuts <- stats::cutree(h_clust, k = k)
## Bind cut tree to data frame
data_final <-
data_cluster%>%
select(PersonId) %>%
cbind("cluster" = cuts) %>%
left_join(data, by = "PersonId")
## Return
if(return == "data"){
return(data_final)
} else if(return == "table"){
## Count table
count_tb <-
data_final %>%
group_by(cluster) %>%
summarise(n = n()) %>%
mutate(prop = n / sum(n))
## Summary statistics
sums_tb <-
data_final %>%
group_by(cluster) %>%
summarise_if(is.numeric,function(x) round(mean(x),1))
count_tb %>%
left_join(sums_tb, by = "cluster") %>%
return()
} else if(return =="plot"){
## Unique person count
## Print count string
count_tb_p <-
data_final %>%
hrvar_count(hrvar = "cluster", return = "table") %>%
arrange(cluster) %>%
mutate(print_str = paste0("cluster ", cluster, " = ", n)) %>%
pull(print_str) %>%
paste(collapse = "; ")
## Use keymetrics_scan() to visualize clusters
data_final %>%
mutate(cluster = factor(cluster)) %>%
keymetrics_scan(hrvar = "cluster") +
labs(title = "Key metrics by personas clusters",
caption = paste(count_tb_p, "\n",
extract_date_range(data, return = "text")))
} else if(return == "hclust"){
return(h_clust)
} else {
stop("Invalid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/personas_hclust.R
|
#' @title Plot a Sample of Working Patterns using Flexibility Index output
#'
#' @description This is a helper function for plotting visualizations for the
#' Flexibility Index using the `data` output from `flex_index()`. This is used
#' within `flex_index()` itself as an internal function.
#'
#' @param data Data frame. Direct data output from `flex_index()`.
#' @param sig_label Character string for identifying signal labels.
#' @param method Character string for determining which plot to return.
#' Options include "sample", "common", and "time". "sample"
#' plots a sample of ten working patterns; "common" plots the ten most common
#' working patterns; "time" plots the Flexibility Index for the group over time.
#' @param start_hour See `flex_index()`.
#' @param end_hour See `flex_index()`.
#' @param mode See `flex_index()`.
#' @import dplyr
#' @import ggplot2
#' @importFrom data.table ":=" "%like%" "%between%"
#'
#' @family Working Patterns
#'
#' @examples
#' \donttest{
#' # Pre-calculate Flexibility Index
#' fi_output <- flex_index(em_data, return = "data")
#'
#' # Examples of how to test the plotting options individually
#' # Sample of 10 work patterns
#' plot_flex_index(fi_output, method = "sample")
#'
#' # 10 most common work patterns
#' plot_flex_index(fi_output, method = "common")
#'
#' # Plot Flexibility Index over time
#' plot_flex_index(fi_output, method = "time")
#' }
#'
#' @return ggplot object. See `method`.
#'
#' @export
plot_flex_index <- function(data,
sig_label = "Signals_sent_",
method = "sample",
start_hour = 9,
end_hour = 17,
mode = "binary"){
## Bindings for variables
TakeBreaks <- NULL
ChangeHours <- NULL
ControlHours <- NULL
FlexibilityIndex <- NULL
## Avoid confusion
sig_label_ <- sig_label
## Table for annotation - plotting only
## Different calculation for results
myTable_legends <-
data %>%
dplyr::summarise_at(vars(TakeBreaks, ChangeHours, ControlHours), ~mean(., na.rm = TRUE), .groups = "drop_last") %>%
dplyr::mutate(FlexibilityIndex = select(., TakeBreaks, ChangeHours, ControlHours) %>% apply(1, mean),
patternRank = 5) # 5 so that it shows right in the middle
## Used for captions
score_tb <-
myTable_legends %>%
dplyr::mutate_at(vars(FlexibilityIndex), ~round(.*100)) %>%
dplyr::mutate_at(vars(TakeBreaks, ChangeHours, ControlHours), ~scales::percent(.))
## Make for pretty printing
myTable_legends <-
myTable_legends %>%
dplyr::mutate(FlexibilityIndex = scales::percent(FlexibilityIndex))
## Main plot
## Different plots if different `method` is specified
if(method == "sample"){
# Sample of ten working patterns
plot_data <-
data %>%
.[sample(nrow(.), size = 10), ]
## Make sure data.table knows we know we're using it
.datatable.aware = TRUE
data_tb <- data.table::as.data.table(data)
plot_title <- "Random sample of 10 Working patterns"
} else if(method == "common"){
# Top ten most common patterns
## Make sure data.table knows we know we're using it
.datatable.aware = TRUE
data_tb <- data.table::as.data.table(data)
plot_title <- "Top 10 Most Common Working patterns"
} else if(method == "time"){
plot_data <- data
} else {
stop("Invalid input value for `method`")
}
## Branch out - sample/common VS time
if(method %in% c("sample", "common")){
if(mode == "binary"){
input_var <- names(data)[grepl(sig_label_, names(data))]
data_tb <- data_tb[, list(WeekCount = .N,
PersonCount = dplyr::n_distinct(PersonId)),
by = input_var]
plot_data <-
data_tb %>%
as.data.frame() %>%
dplyr::arrange(desc(WeekCount)) %>%
slice(1:10)
plot_data_long <-
plot_data %>%
mutate(patternRank = 1:nrow(.)) %>%
dplyr::select(patternRank, dplyr::starts_with(sig_label_)) %>%
purrr::set_names(nm = gsub(pattern = sig_label_, replacement = "", x = names(.))) %>%
purrr::set_names(nm = gsub(pattern = "_.+", replacement = "", x = names(.)))
} else if(mode == "prop"){
input_var <- names(data)[grepl(sig_label_, names(data))]
sig_label_ <- gsub(
pattern = "_sent_",
replacement = "_ori_",
x = sig_label_
)
## 00, 01, 02, etc.
hours_col <- pad2(x = seq(0,23))
# Use `mutate()` method
# Will get 10 IDs, not 10 rows
# NOTE: `input_var` is used to identify a distinct work pattern
plot_data <-
data_tb %>%
data.table::as.data.table() %>%
.[, `:=`(WeekCount = .N,
PersonCount = dplyr::n_distinct(PersonId),
Id = .GRP), # group id assignment
by = input_var] %>%
dplyr::arrange(desc(WeekCount))
plot_data <-
plot_data %>%
dplyr::select(Id, dplyr::contains("_ori_"), WeekCount) %>%
purrr::set_names(nm = gsub(
pattern = ".+_ori_",
replacement = "",
x = names(.)
)) %>%
purrr::set_names(nm = gsub(
pattern = "_.+",
replacement = "",
x = names(.)
)) %>%
# Need aggregation
.[, Signals_Total := rowSums(.SD), .SDcols = hours_col] %>%
.[, c(hours_col) := .SD / Signals_Total, .SDcols = hours_col] %>%
.[, Signals_Total := NULL] %>% # Remove unneeded column
.[, lapply(.SD, mean, na.rm = TRUE), .SDcols = hours_col, by = list(Id, WeekCount)]
plot_data_long <-
plot_data %>%
dplyr::arrange(desc(WeekCount)) %>%
dplyr::mutate(patternRank = 1:nrow(.)) %>%
slice(1:10)
} else {
stop("Invalid value to `mode`")
}
plot_data_long %>%
plot_hourly_pat(
start_hour = start_hour,
end_hour = end_hour,
legend = myTable_legends,
legend_label = "FlexibilityIndex",
legend_text = paste("Observed activity"),
rows = 10, # static
title = "Work Patterns and Flexibility Index",
subtitle = paste0(plot_title,
"\n",
"Group Flexibility Index: ",
score_tb$FlexibilityIndex),
caption = paste0("% Taking Breaks: ", score_tb$TakeBreaks, "\n",
"% Change Hours: ", score_tb$ChangeHours, "\n",
"% Keep Hours Under Control: ", score_tb$ControlHours, "\n",
extract_date_range(data, return = "text")),
ylab = "Work patterns"
)
# plot_data %>%
# mutate(patternRank = 1:nrow(.)) %>%
# dplyr::select(patternRank, dplyr::starts_with(sig_label_)) %>%
# purrr::set_names(nm = gsub(pattern = sig_label_, replacement = "", x = names(.))) %>%
# purrr::set_names(nm = gsub(pattern = "_.+", replacement = "", x = names(.))) %>%
# tidyr::gather(Hours, Freq, -patternRank) %>%
# ggplot2::ggplot(ggplot2::aes(x = Hours, y = patternRank, fill = Freq)) +
# ggplot2::geom_tile(height=.5) +
# ggplot2::ylab("Work Patterns") +
# ggplot2::scale_fill_gradient2(low = "white", high = "#1d627e") +
# ggplot2::scale_y_reverse(breaks=seq(1,10)) +
# wpa::theme_wpa_basic() +
# ggplot2::theme(legend.position = "none") +
# ggplot2::annotate("text",
# y = myTable_legends$patternRank,
# x = 26.5,
# label = scales::percent(myTable_legends$FlexibilityIndex), size = 3) +
# ggplot2::annotate("rect",
# xmin = 25,
# xmax = 28,
# ymin = 0.5,
# ymax = 10 + 0.5,
# alpha = .2) +
# ggplot2::annotate("rect",
# xmin = 0.5,
# xmax = start_hour + 0.5,
# ymin = 0.5,
# ymax = 10 + 0.5,
# alpha = .1,
# fill = "gray50") +
# ggplot2::annotate("rect",
# xmin = end_hour + 0.5,
# xmax = 24.5,
# ymin = 0.5,
# ymax = 10 + 0.5,
# alpha = .1,
# fill = "gray50") +
# ggplot2::labs(title = "Work Patterns and Flexibility Index",
# subtitle = paste0(plot_title,
# "\n",
# "Group Flexibility Index: ", score_tb$FlexibilityIndex),
# caption = paste0("% Taking Breaks: ", score_tb$TakeBreaks, "\n",
# "% Change Hours: ", score_tb$ChangeHours, "\n",
# "% Keep Hours Under Control: ", score_tb$ControlHours, "\n",
# extract_date_range(data, return = "text")))
} else if(method == "time"){
plot_data %>%
group_by(Date) %>%
summarise_at(vars(FlexibilityIndex), ~mean(., na.rm = TRUE)) %>%
wpa::create_line_asis(date_var = "Date",
metric = "FlexibilityIndex",
title = "Flexibility Index",
subtitle = paste0("Score over time\n",
"Average Flexibility Index: ", score_tb$FlexibilityIndex),
xlab = "Flexibility Index",
caption = paste0("% Taking Breaks: ", score_tb$TakeBreaks, "\n",
"% Change Hours: ", score_tb$ChangeHours, "\n",
"% Keep Hours Under Control: ", score_tb$ControlHours, "\n",
extract_date_range(data, return = "text")))
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/plot_flex_index.R
|
#' @title
#' Internal function for plotting the hourly activity patterns.
#'
#' @description
#' This is used within `plot_flex_index()` and `workpatterns_rank()`.
#'
#' @param data Data frame containing three columns:
#' - `patternRank`
#' - `Hours`
#' - `Freq`
#'
#' @param start_hour Numeric value to specify expected start hour.
#' @param end_hour Numeric value to specify expected end hour.
#'
#' @param legend Data frame containing the columns:
#' - `patternRank`
#' - Any column to be used in the grey label box, supplied to `legend_label`
#'
#' @param legend_label String specifying column to display in the grey label
#' box
#'
#' @param legend_text String to be used in the bottom legend label.
#'
#' @param rows Number of rows to show in plot.
#' @param title String to specify plot title.
#' @param subtitle String to specify plot subtitle.
#' @param caption String to specify plot caption.
#' @param ylab String to specify plot y-axis label.
#'
#' @export
plot_hourly_pat <- function(
data,
start_hour,
end_hour,
legend,
legend_label,
legend_text = "Observed activity",
rows,
title,
subtitle,
caption,
ylab = paste("Top", rows, "activity patterns")
){
## 00, 01, 02, etc.
hours_col <- pad2(x = seq(0,23))
data %>%
utils::head(rows) %>%
tidyr::pivot_longer(
cols = hours_col,
names_to = "Hours",
values_to = "Freq"
) %>%
ggplot2::ggplot(ggplot2::aes(x = Hours, y = patternRank, fill = Freq)) +
ggplot2::geom_tile(height = .5) +
ggplot2::ylab(ylab) +
ggplot2::scale_y_reverse(expand = c(0, 0), breaks = seq(1, rows)) +
wpa::theme_wpa_basic() +
ggplot2::scale_x_discrete(position = "top")+
ggplot2::theme(
axis.title.x = element_blank(),
axis.line = element_blank(),
axis.ticks = element_blank()
) +
# Not operational if not binary
scale_fill_continuous(
guide = "legend",
low = "white",
high = "#1d627e",
breaks = 0:1,
name = "",
labels = c("", legend_text)
) +
ggplot2::annotate(
"text",
y = legend$patternRank,
x = 26.5,
label = legend[[legend_label]],
size = 3
)+
ggplot2::annotate("rect",
xmin = 25,
xmax = 28,
ymin = 0.5,
ymax = rows + 0.5,
alpha = .2) +
ggplot2::annotate("rect",
xmin = 0.5,
xmax = start_hour + 0.5,
ymin = 0.5,
ymax = rows + 0.5,
alpha = .1,
fill = "gray50") +
ggplot2::annotate("rect",
xmin = end_hour + 0.5,
xmax = 24.5,
ymin = 0.5,
ymax = rows + 0.5,
alpha = .1,
fill = "gray50") +
labs(
title = title,
subtitle = subtitle,
caption = caption
)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/plot_hourly_pat.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Remove outliers from a person query across time
#'
#' @description
#' `r lifecycle::badge('experimental')`
#'
#' This function takes in a selected metric and uses z-score (number of standard
#' deviations) to identify and remove outlier weeks for individuals across time.
#' There are applications in this for removing weeks with abnormally low
#' collaboration activity, e.g. holidays. Retains metrics with z > -2.
#'
#' Function is based on `identify_outlier()`, but implements a more elaborate
#' approach as the outliers are identified and removed **with respect to each
#' individual**, as opposed to the group. Note that `remove_outliers()` has a
#' longer runtime compared to `identify_outlier()`.
#'
#' @author Mark Powers <mark.powers@@microsoft.com>
#'
#' @details
#' For mature functions to remove common outliers, please see the following:
#' - `identify_holidayweeks()`
#' - `identify_nkw()`
#' - `identify_inactiveweeks`
#'
#' @param data A Standard Person Query dataset in the form of a data frame.
#' @param metric Character string containing the name of the metric,
#' e.g. "Collaboration_hours"
#'
#' @import dplyr
#'
#' @family Data Validation
#'
#' @return
#' Returns a new data frame, "cleaned_data" with all metrics,
#' having removed the person-weeks that are below 2 standard
#' deviations of each individual's collaboration activity.
#'
#' @export
#'
remove_outliers <- function(data, metric = "Collaboration_hours") {
remove_outlier <- function(data, metric = "Collaboration_hours") {
output <-
identify_outlier(data, group_var = "Date", metric = metric)
output %>%
filter(zscore > -2) %>%
select(Date) %>%
mutate(PersonId = data$PersonId[[1]]) # Take first one
}
p_list <-
data %>%
select(Date, PersonId, metric) %>%
group_split(PersonId)
personweeks <-
p_list[1:length(p_list)] %>% # Increase as required
purrr::map(remove_outlier) %>%
bind_rows() %>%
mutate(key = paste(Date, PersonId)) %>%
select(key)
cleaned_data <-
data %>%
mutate(key = paste(Date, PersonId)) %>%
filter(key %in% personweeks$key) %>%
select(-key)
return(cleaned_data)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/remove_outliers.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Sample Standard Person Query dataset
#'
#' @description
#' A dataset generated from a Standard Person Query from Workplace Analytics.
#'
#' @family Data
#'
#' @return data frame.
#'
#' @format A data frame with 4403 rows and 66 variables:
#' \describe{
#' \item{PersonId}{ }
#' \item{Date}{ }
#' \item{Workweek_span}{Time between the person's first sent email or meeting attended and
#' the last email or meeting for each day of the work week.}
#' \item{Meetings_with_skip_level}{ }
#' \item{Meeting_hours_with_skip_level}{ }
#' \item{Generated_workload_email_hours}{ }
#' \item{Generated_workload_email_recipients}{ }
#' \item{Generated_workload_instant_messages_hours}{ }
#' \item{Generated_workload_instant_messages_recipients}{ }
#' \item{Generated_workload_call_hours}{ }
#' \item{Generated_workload_call_participants}{ }
#' \item{Generated_workload_calls_organized}{ }
#' \item{External_network_size}{ }
#' \item{Internal_network_size}{ }
#' \item{Networking_outside_company}{ }
#' \item{Networking_outside_organization}{ }
#' \item{After_hours_meeting_hours}{ }
#' \item{Open_1_hour_block}{ }
#' \item{Open_2_hour_blocks}{ }
#' \item{Total_focus_hours}{ }
#' \item{Low_quality_meeting_hours}{ }
#' \item{Total_emails_sent_during_meeting}{ }
#' \item{Meetings}{ }
#' \item{Meeting_hours}{ }
#' \item{Conflicting_meeting_hours}{ }
#' \item{Multitasking_meeting_hours}{ }
#' \item{Redundant_meeting_hours__lower_level_}{ }
#' \item{Redundant_meeting_hours__organizational_}{ }
#' \item{Time_in_self_organized_meetings}{ }
#' \item{Meeting_hours_during_working_hours}{ }
#' \item{Generated_workload_meeting_attendees}{ }
#' \item{Generated_workload_meeting_hours}{ }
#' \item{Generated_workload_meetings_organized}{ }
#' \item{Manager_coaching_hours_1_on_1}{ }
#' \item{Meetings_with_manager}{ }
#' \item{Meeting_hours_with_manager}{ }
#' \item{Meetings_with_manager_1_on_1}{ }
#' \item{Meeting_hours_with_manager_1_on_1}{ }
#' \item{After_hours_email_hours}{ }
#' \item{Emails_sent}{ }
#' \item{Email_hours}{Number of hours the person spent sending and receiving emails.}
#' \item{Working_hours_email_hours}{ }
#' \item{After_hours_instant_messages}{ }
#' \item{Instant_messages_sent}{ }
#' \item{Instant_Message_hours}{ }
#' \item{Working_hours_instant_messages}{ }
#' \item{After_hours_collaboration_hours}{ }
#' \item{Collaboration_hours}{ }
#' \item{Collaboration_hours_external}{ }
#' \item{Working_hours_collaboration_hours}{ }
#' \item{After_hours_in_calls}{ }
#' \item{Total_calls}{ }
#' \item{Call_hours}{ }
#' \item{Working_hours_in_calls}{ }
#' \item{Domain}{ }
#' \item{FunctionType}{ }
#' \item{LevelDesignation}{ }
#' \item{Layer}{ }
#' \item{Region}{ }
#' \item{Organization}{ }
#' \item{zId}{ }
#' \item{attainment}{ }
#' \item{TimeZone}{ }
#' \item{HourlyRate}{ }
#' \item{IsInternal}{ }
#' \item{IsActive}{ }
#'
#' ...
#' }
"sq_data"
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/sq_data.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Standardise variable names to a Standard Person Query
#'
#' @description
#' This function standardises the variable names to a Standard Person
#' Query, where the standard use case is to pass a Ways of Working Assessment
#' Query to the function.
#'
#' @details
#' The following standardisation steps are taken:
#' - `Collaboration_hrs` -> `Collaboration_hours`
#' - `Instant_message_hours` -> `Instant_Message_hours`
#'
#' @param data A Ways of Working Assessment query to pass through as a data
#' frame.
#'
#' @return
#' data frame containing the formatted query passed to the function.
#'
#' @family Data Validation
#' @family Import and Export
#'
#' @export
standardise_pq <- function(data){
if(identify_query(data) != "Ways of Working Assessment Query"){
stop("Currently only Ways of Working Assessment Query to Standard Person Query
conversions are supported.")
}
## Message what the function is doing
message("Standardising variable names with a Person Query...")
## Collaboration_hours
if(!("Collaboration_hours" %in% names(data)) &
("Collaboration_hrs" %in% names(data))){
data <- data %>% rename(Collaboration_hours = "Collaboration_hrs")
message("`Collaboration_hrs` renamed to `Collaboration_hours`")
} else if(!("Collaboration_hrs" %in% names(data)) &
("Collaboration_hours" %in% names(data))){
# Do nothing
} else {
warning("No collaboration hour metric exists in the data.")
}
## Instant_Message_hours
if(!("Instant_message_hours" %in% names(data)) &
("Instant_Message_hours" %in% names(data))){
# Do nothing
} else if(!("Instant_Message_hours" %in% names(data)) &
("Instant_message_hours" %in% names(data))){
data <- data %>% rename(Instant_Message_hours = "Instant_message_hours")
message("`Instant_message_hours` renamed to `Instant_Message_hours`")
} else {
warning("No instant message hour metric exists in the data.")
}
return(data)
}
#' @rdname standardise_pq
#' @export
standardize_pq <- standardise_pq
#' @title Standardise variable names for Standard Person Query Quietly for
#' `Collaboration_hours`
#'
#' @noRd
#'
qui_stan_c <- function(data){
if(!("Collaboration_hours" %in% names(data)) &
("Collaboration_hrs" %in% names(data))){
data <- data %>% mutate(Collaboration_hours = Collaboration_hrs)
# message("Adding `Collaboration_hours` column based on `Collaboration_hrs`")
}
return(data)
}
#' @title Standardise variable names for Standard Person Query Quietly for
#' `Instant_Message_hours`
#'
#' @noRd
#'
qui_stan_im <- function(data){
if(!("Instant_Message_hours" %in% names(data)) &
("Instant_message_hours" %in% names(data))){
data <- data %>% mutate(Instant_Message_hours = Instant_message_hours)
# message("Adding `Instant_Message_hours` column based on `Instant_message_hours`")
}
return(data)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/standardise_pq.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Create a new logical variable that classifies meetings by patterns in
#' subject lines
#'
#' @description Take a meeting query with subject lines and create a new
#' TRUE/FALSE column which classifies meetings by a provided set of patterns in
#' the subject lines.
#'
#' @param data A Meeting Query dataset in the form of a data frame.
#' @param var_name String containing the name of the new column to be created.
#' @param keywords Character vector containing the keywords to match.
#' @param pattern String to use for regular expression matching instead of
#' `keywords`. When both `keywords` and `pattern` are supplied, `pattern`
#' takes priority and is used instead.
#' @param ignore_case Logical value to determine whether to ignore case when
#' performing pattern matching.
#' @param return String specifying what output to return.
#'
#' @examples
#' class_df <-
#' mt_data %>%
#' subject_classify(
#' var_name = "IsSales",
#' keywords = c("sales", "marketing")
#' )
#'
#' class_df %>% dplyr::count(IsSales)
#'
#' # Return a table directly
#' mt_data %>% subject_classify(pattern = "annual", return = "table")
#'
#' @export
subject_classify <- function(data,
var_name = "class",
keywords = NULL,
pattern = NULL,
ignore_case = FALSE,
return = "data"
){
if(is.null(pattern) & is.null(keywords)){
stop("Please supply a character vector to either `keywords` or `pattern`.")
} else if(is.null(pattern)){
message("Using character vector supplied to `keywords`.")
pattern <- paste(keywords, collapse = "|")
}
# Create logical variable and match pattern ------------------------------
data[[var_name]] <-
grepl(
pattern = pattern,
x = data[["Subject"]],
ignore.case = ignore_case
)
if(return == "data"){
message("Returning data frame with additional column: ",
var_name)
data
} else if(return == "table"){
dplyr::count(data, !!sym(var_name))
} else {
stop("Invalid value to `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/subject_classify.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title
#' Count top words in subject lines grouped by a custom attribute
#'
#' @description `r lifecycle::badge('experimental')`
#'
#' This function generates a matrix of the top occurring words in meetings,
#' grouped by a specified attribute such as organisational attribute, day of the
#' week, or hours of the day.
#'
#' @param data A Meeting Query dataset in the form of a data frame.
#' @param hrvar String containing the name of the HR Variable by which to split
#' metrics. Note that the prefix `'Organizer_'` or equivalent will be
#' required.
#' @param mode String specifying what variable to use for grouping subject
#' words. Valid values include:
#' - `"hours"`
#' - `"days"`
#' - `NULL` (defaults to `hrvar`)
#' When the value passed to `mode` is not `NULL`, the value passed to `hrvar`
#' will be discarded and instead be over-written by setting specified in `mode`.
#' @param top_n Numeric value specifying the top number of words to show.
#' @inheritParams tm_clean
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#' - `"data"`
#'
#' See `Value` for more information.
#' @param weight String specifying the column name of a numeric variable for
#' weighting data, such as `"Invitees"`. The column must contain positive
#' integers. Defaults to `NULL`, where no weighting is applied.
#' @param stopwords A character vector OR a single-column data frame labelled
#' `'word'` containing custom stopwords to remove.
#' @param ... Additional parameters to pass to `tm_clean()`.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: 'ggplot' object. A heatmapped grid.
#' - `"table"`: data frame. A summary table for the metric.
#' - `"data"`: data frame.
#'
#' @import dplyr
#' @import ggplot2
#'
#' @examples
#' \donttest{
#' # return a heatmap table for words
#' mt_data %>% subject_scan(hrvar = "Organizer_Organization")
#'
#' # return a heatmap table for ngrams
#' mt_data %>%
#' subject_scan(
#' hrvar = "Organizer_Organization",
#' token = "ngrams",
#' n = 2)
#'
#' # return raw table format
#' mt_data %>% subject_scan(hrvar = "Organizer_Organization", return = "table")
#'
#' # grouped by hours
#' mt_data %>% subject_scan(mode = "hours")
#'
#' # grouped by days
#' mt_data %>% subject_scan(mode = "days")
#' }
#' @export
subject_scan <- function(data,
hrvar,
mode = NULL,
top_n = 10,
token = "words",
return = "plot",
weight = NULL,
stopwords = NULL,
...){
# weighting -------------------------------------------------------
if(!is.null(weight)){
d_weight <- data[[weight]]
if(any(is.na(d_weight) | d_weight <= 0 | d_weight %% 1 != 0)){
stop("Please check 'weight' variable.")
}
# duplicate rows according to numeric weight
# numeric weight must be an integer
data_w <- data[rep(seq_len(nrow(data)), d_weight),]
} else {
data_w <- data
}
# modes -----------------------------------------------------------
if(is.null(mode)){
# do nothing
} else if(mode == "hours"){
# Default variable in meeting query
StartTimeUTC <- NULL
data_w <-
data_w %>%
mutate(HourOfDay = substr(StartTimeUTC, start = 1, stop = 2) %>%
as.numeric()) %>%
mutate(HourOfDay =
case_when(HourOfDay > 19 ~ "After 7PM",
HourOfDay >= 17 ~ "5 - 7 PM",
HourOfDay >= 14 ~ "2 - 5 PM",
HourOfDay >= 11 ~ "11AM - 2 PM",
HourOfDay >= 9 ~ "9 - 11 AM",
TRUE ~ "Before 9 AM"
) %>%
factor(
levels = c(
"Before 9 AM",
"9 - 11 AM",
"11AM - 2 PM",
"2 - 5 PM",
"5 - 7 PM",
"After 7PM"
)
))
hrvar <- "HourOfDay"
} else if(mode == "days"){
# Variable in meeting data
StartDate <- NULL
data_w <-
data_w %>%
mutate(DayOfWeek = weekdays(StartDate) %>%
factor(
levels = c(
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
)
))
hrvar <- "DayOfWeek"
}
# long table -------------------------------------------------------
out_tb_long <-
data_w %>%
group_split(!!sym(hrvar)) %>%
purrr::map(function(x){
dow <- x[[hrvar]][1]
long_t <- tm_clean(
x,
token = token,
stopwords = stopwords,
...) %>%
filter(!is.na(word))
long_t %>%
count(word) %>%
arrange(desc(n)) %>%
utils::head(top_n) %>%
mutate(group = dow)
}) %>%
bind_rows()
# wide table -------------------------------------------------------
out_tb_wide <-
out_tb_long %>%
group_split(group) %>%
purrr::map(function(x){
dow <- x[["group"]][1]
x %>%
rename(
!!sym(paste0(dow, "_word")) := "word",
!!sym(paste0(dow, "_n")) := "n"
) %>%
select(-group)
}) %>%
bind_cols()
# return simple table -----------------------------------------------
out_simple <-
out_tb_wide %>%
select(-ends_with("_n")) %>%
purrr::set_names(nm = gsub(pattern = "_word", replacement = "",
x = names(.)))
# return chunk -------------------------------------------------------
if(return == "plot"){
out_tb_long %>%
mutate(n = maxmin(n)) %>%
arrange(desc(n)) %>%
group_by(group) %>%
mutate(id = 1:n()) %>%
ungroup() %>%
ggplot(aes(x = group, y = id)) +
geom_tile(aes(fill = n)) +
geom_text(aes(label = word), size = 3) +
scale_fill_gradient2(low = rgb2hex(7, 111, 161),
mid = rgb2hex(241, 204, 158),
high = rgb2hex(216, 24, 42),
midpoint = 0.5,
breaks = c(0, 0.5, 1),
labels = c("Low", "", "High"),
limits = c(0, 1),
name = "Frequency") +
scale_x_discrete(position = "top") +
scale_y_reverse() +
theme_wpa_basic() +
theme(axis.text.x = element_text(angle = 45, hjust = 0),
plot.title = element_text(color="grey40", face="bold", size=20),
axis.text.y = element_blank()) +
labs(
title = "Top terms",
subtitle = paste("By", camel_clean(hrvar)),
y = "Top terms by frequency in Subject",
x = ""
)
} else if(return == "table"){
out_simple
} else if(return == "data"){
out_tb_wide
} else {
stop("Invalid input to return.")
}
}
#' @rdname subject_scan
#' @export
tm_scan <- subject_scan
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/subject_scan.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Scan meeting subject and highlight items for review
#'
#' @description
#' This functions scans a meeting query and highlights meetings with subjects
#' that include common exlusion terms. It is intended to be used by an analyst
#' to validate raw data before conducting additional analysis. Returns a summary
#' in the console by default. Additional option to return the underlying data
#' with a flag of items for review.
#'
#'
#' @family Data Validation
#' @family Text-mining
#'
#' @param data A meeting query in the form of a data frame.
#' @param return A string specifying what to return. Returns a message in the
#' console by default, where `'text'` is passed in `return`. When `'table'` is
#' passed, a summary table with common terms found is printed. When `'data'`
#' is passed, a the original data with an additional flag column is returned
#' as a data frame.
#'
#' @return Returns a message in the console by default, where `'text'` is passed
#' in `return`. When `'table'` is passed, a summary table with common terms
#' found is printed. When `'data'` is passed, a the original data with an
#' additional flag column is returned as a data frame.
#'
#' @export
subject_validate <- function(data, return = "text"){
## Check inputs
required_variables <- c("Subject")
## Error message if variables are not present. Nothing happens if all present
data %>% check_inputs(requirements = required_variables)
# Define common "test" words:
reminders <-
c(
"departure",
"flight",
"cancelled",
"room",
"booking",
"placeholder",
"save the date",
"reminder",
"change password",
"time sheet",
"timesheet",
"workday time",
"dental",
"dentist",
"doctor",
"dr" ,
"dr." ,
"medical" ,
"physical therapy" ,
"surgery" ,
"leave" ,
"day off" ,
"from home" ,
"half day" ,
"office closed" ,
"maternity",
"OOF" ,
"OOO" ,
"ooto" ,
"out of office" ,
"paternity" ,
"PTO" ,
"telework" ,
"sick leave" ,
"time off" ,
"vacation" ,
"WFH",
"enter time",
"timecard",
"time card",
"log in",
"log out",
"payday",
"pay day",
"go home",
"fill out",
"clock in",
"clock out",
"pay bills"
)
leisure <-
c(
"baseball",
"basketball",
"bball",
"tennis",
"book club",
"football",
"pilates",
"soccer",
"swim",
"yoga",
"zumba",
"game",
"gym",
"meditation",
"walk dog",
"haircut",
"toastmasters"
)
holidays <-
c(
"diwali",
"easter",
"holiday",
"independence day",
"labor day",
"labour day",
"new year",
"yom kippur"
)
socials <-
c(
"party",
"birthday",
"bday",
"b day",
"church",
"dinner",
"school",
"happy hour",
"potluck",
"bagel",
"baby shower"
)
test_words <- append(reminders, leisure)
test_words <- append(test_words, holidays)
test_words <- append(test_words, socials)
# take suubjet lines to lower case.names
data$Subject <- tolower(data$Subject)
# 3.3 subject lines to lower case.names
results <-
test_words %>%
purrr::map(function(x){
index <- grepl(pattern = x, x = data$Subject)
CheckSum <- sum(index)
CheckMean <- mean(index) * 100
data.frame(Word = x,
Cases = CheckSum,
Perc = round(CheckMean, digits=2))
}) %>% bind_rows()
results <-
results %>%
arrange(desc(Cases)) %>%
filter(Cases > 0)
# 3.3 Flag meetings that have an issue:
Pattern <- paste(test_words, collapse="|")
data$subjectFlag <- grepl(Pattern, data$Subject)
table(data$subjectFlag)
# 3.4 Display error
## Get statistics
TotalN <- nrow(data)
FlagN <- sum(data$subjectFlag, na.rm = TRUE)
FlagProp <- mean(data$subjectFlag, na.rm = TRUE)
FlagPropF <- paste0(round(FlagProp * 100, 1), "%") # Formatted
## Flag Messages
Warning_Message <- paste("[Warning] ", FlagN," meetings (",FlagPropF, "of ", TotalN, ") require your attention as they contain common exclusion terms.")
Pass_Message <- paste("[Pass] No subject lines with common exclusion terms are present in the ", TotalN, " meetings analysed.")
if(FlagN >= 0 ){
FlagMessage <- Warning_Message
} else if(FlagN == 0){
FlagMessage <- Pass_Message
}
if(return == "text"){
FlagMessage
} else if(return == "table"){
return(results)
} else if(return == "data"){
return(data)
}else {
stop("Please enter a valid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/subject_validate.r
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Generate Meeting Text Mining report in HTML for Common Exclusion Terms
#'
#' @description This functions creates a text mining report in HTML based on
#' Meeting Subject Lines for data validation. It scans a meeting query and
#' highlights meetings with subjects that include common exlusion terms. It is
#' intended to be used by an analyst to validate raw data before conducting
#' additional analysis. Returns a HTML report by default.
#'
#' @family Data Validation
#' @family Text-mining
#' @family Reports
#'
#' @param data A Meeting Query dataset in the form of a data frame.
#' @param path Pass the file path and the desired file name, _excluding the file
#' extension_. For example, `"meeting text mining report"`.
#' @param timestamp Logical vector specifying whether to include a timestamp in
#' the file name. Defaults to `TRUE`.
#' @param keep A numeric vector specifying maximum number of words to keep.
#' @param seed A numeric vector to set seed for random generation.
#'
#'
#' @inherit generate_report return
#'
#' @export
subject_validate_report <- function(data,
path = "Subject Lines Validation Report",
timestamp = TRUE,
keep = 100,
seed = 100){
## Create timestamped path (if applicable)
if(timestamp == TRUE){
newpath <- paste(path, wpa::tstamp())
} else {
newpath <- path
}
# Get Results
test_data <- data %>% subject_validate(return="data") %>% filter(subjectFlag==1)
results <- data %>% subject_validate(return="table")
# Set outputs
output_list <-
list(data %>% subject_validate(return="table"),
test_data %>% tm_wordcloud(),
test_data %>% tm_freq(token = "words"),
test_data %>% tm_freq(token = "words", return = "table"),
test_data %>% tm_freq(token = "ngrams"),
test_data %>% tm_freq(token = "ngrams", return = "table"),
test_data %>% tm_cooc(),
test_data %>% tm_cooc(return="table")) %>%
purrr::map_if(is.data.frame, create_dt)
# Set header titles
title_list <-
c("Exclusion Terms Identified",
"Related Words",
"",
"",
"Common Phrases",
"",
"Word Co-occurrence",
"")
# Set header levels
n_title <- length(title_list)
levels_list <- rep(3, n_title)
# Generate report
generate_report(title = "Subject Lines Validation Report",
filename = newpath,
outputs = output_list,
titles = title_list,
subheaders = rep("", n_title),
echos = rep(FALSE, n_title),
levels = levels_list,
theme = "cosmo",
preamble = "")
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/subject_validate_report.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Check whether a data frame contains all the required variable
#'
#' @description
#' Checks whether a data frame contains all the required variables.
#' Matching works via variable names, and used to support individual
#' functions in the package. Not used directly.
#'
#' @param input Pass a data frame for checking
#' @param requirements A character vector specifying the required variable names
#' @param return A character string specifying what to return.
#' The default value is "stop". Also accepts "names" and "warning".
#'
#'
#' @return The default behaviour is to return an error message, informing the
#' user what variables are not included. When `return` is set to "names", a
#' character vector containing the unmatched variable names is returned.
#'
#' @family Support
#'
#' @examples
#'
#' # Return error message
#' \dontrun{
#' check_inputs(iris, c("Sepal.Length", "mpg"))
#' }
#'
#' #' # Return warning message
#' check_inputs(iris, c("Sepal.Length", "mpg"), return = "warning")
#'
#' # Return variable names
#' check_inputs(iris, c("Sepal.Length", "Sepal.Width", "RandomVariable"), return = "names")
#'
#' @export
check_inputs <- function(input, requirements, return = "stop"){
## Get variable names of input df
nm_input <- names(input)
## Get logical vector
test_results <- requirements %in% nm_input
## Return FALSE results
not_in <- requirements[!test_results]
## Comma separated
not_in_p <- paste(not_in, collapse = ", ")
## Create warning message
warning_string <-
paste("The following variables are not included in the input data frame:\n",
not_in_p)
if(length(not_in) > 0){
if(return == "names"){
return(not_in)
} else if(return == "warning"){
warning(warning_string)
} else if(return == "stop"){
stop(warning_string)
} else {
stop("Invalid input: please check `return` argument for `check_inputs()`")
}
}
}
#' @title Convert "CamelCase" to "Camel Case"
#'
#' @description
#' Convert a text string from the format "CamelCase" to "Camel Case".
#' This is used for converting variable names such as
#' "LevelDesignation" to "Level Designation" for the purpose
#' of prettifying plot labels.
#'
#' @param string A string vector in 'CamelCase' format to format
#'
#' @family Support
#'
#' @examples
#' camel_clean("NoteHowTheStringIsFormatted")
#'
#' @return Returns a formatted string.
#'
#' @export
camel_clean <- function(string){
gsub("([a-z])([A-Z])", "\\1 \\2", string)
}
#' @title Convert rgb to HEX code
#'
#' @param r,g,b Values that correspond to the three RGB parameters
#'
#' @family Support
#'
#' @return Returns a string containing a HEX code.
#'
#' @export
rgb2hex <- function(r,g,b){
grDevices::rgb(r, g, b, maxColorValue = 255)
}
#' @title Extract date period
#'
#' @description
#' Return a data frame with the start and end date
#' of the query data by default. There are options to return a descriptive
#' string, which is used in the caption of plots in this package.
#'
#' @param data Data frame containing a query to pass through.
#' The data frame must contain a `Date` column.
#' Accepts a Person query or a Meeting query.
#'
#' @param return String specifying what output to return.
#' Returns a table by default ("table"), but allows returning
#' a descriptive string ("text").
#'
#' @family Support
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"table"`: data frame. A summary table containing the start and end date
#' for the dataset.
#' - `"text"`: string. Contains a descriptive string on the start and end date
#' for the dataset.
#'
#' @export
extract_date_range <- function(data, return = "table"){
if("Date" %in% names(data)){
date_var <- as.Date(data$Date, "%m/%d/%Y")
} else if(all(c("StartDate", "EndDate") %in% names(data))){
## meeting query
date_var <- c(data$StartDate, data$EndDate)
date_var <- as.Date(date_var, "%m/%d/%Y")
} else {
stop("Error: no date variable found.")
}
myPeriod <-
data.frame(Start = min(date_var),
End = max(date_var))
## Alternative return
if(return == "table"){
myPeriod
} else if(return == "text"){
paste("Data from week of", myPeriod$Start, "to week of", myPeriod$End)
}
}
#' @title Add comma separator for thousands
#'
#' @description
#' Takes a numeric value and returns a character value
#' which is rounded to the whole number, and adds a comma
#' separator at the thousands. A convenient wrapper function
#' around `round()` and `format()`.
#'
#' @param x A numeric value
#'
#' @return Returns a formatted string.
#'
#' @export
comma <- function(x){
x <- round(x, 0)
format(x, nsmall = 0, big.mark=",")
}
#' @title Check whether package is installed and return an error message
#'
#' @description Checks whether a package is installed in the user's machine
#' based on a search on the package name string. If the package is not
#' installed, an error message is returned.
#'
#' @param pkgname String containing the name of the package to check whether is
#' installed.
#'
#' @noRd
#'
check_pkg_installed <- function(pkgname) {
mtry <- try(find.package(package = pkgname))
if (inherits(mtry, "try-error")) {
stop(
paste0(
"\n\nPackage ", wrap(pkgname, wrapper = "`"),
" is required to run this function and is currently not installed.\n",
"Please install package ",
wrap(pkgname, wrapper = "`"),
" to proceed. "
)
)
}
}
#' @title Wrap text based on character threshold
#'
#' @description Wrap text in visualizations according to a preset character
#' threshold. The next space in the string is replaced with `\n`, which will
#' render as next line in plots and messages.
#'
#' @param x String to wrap text
#' @param threshold Numeric, defaults to 15. Number of character units by which
#' the next space would be replaced with `\n` to move text to next line.
#'
#' @examples
#' wrapped <- wrap_text(
#' "The total entropy of an isolated system can never decrease."
#' )
#' message(wrapped)
#'
#' @export
wrap_text <- function(x, threshold = 15){
patt <- paste0(
'(.{1,',
threshold,
'})(\\s|$)'
)
gsub(
pattern = patt,
replacement = '\\1\n',
x = x
)
}
#' @title
#' Create the two-digit zero-padded format
#'
#' @param x numeric value or vector with maximum two characters.
#'
#' @return
#' Numeric value containing two-digit zero-padded values.
#'
#' @export
pad2 <- function(x){
x <- as.character(x)
ifelse(nchar(x) == 1, paste0("0", x), x)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/supporting_functions.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Main theme for 'wpa' visualisations
#'
#' @description
#' A theme function applied to 'ggplot' visualisations in 'wpa'.
#' Install and load 'extrafont' to use custom fonts for plotting.
#'
#' @param font_size Numeric value that prescribes the base font size
#' for the plot. The text elements are defined relatively to this
#' base font size. Defaults to 12.
#'
#' @param font_family Character value specifying the font family
#' to be used in the plot. The default value is `"Segoe UI"`. To ensure
#' you can use this font, install and load {extrafont} prior to
#' plotting. There is an initialisation process that is described by:
#' <https://stackoverflow.com/questions/34522732/changing-fonts-in-ggplot2>
#'
#' @import ggplot2
#'
#' @family Themes
#'
#' @return
#' Returns a ggplot object with the applied theme.
#'
#' @export
theme_wpa <- function(font_size = 12, font_family = "Segoe UI"){
bg_colour <- "#FFFFFF"
bg_colour2 <- "#CCCCCC" # light grey
text_colour <- "grey40"
text_small_dark <- element_text(size = font_size - 2, colour = text_colour, face = "plain")
text_small_light <- element_text(size = font_size - 2, colour = "#FFFFFF", face = "plain")
text_normal <- element_text(size = font_size + 2, colour = text_colour, face = "plain")
text_italic <- element_text(size = font_size + 2, colour = text_colour, face = "italic")
text_bold <- element_text(size = font_size + 2, colour = text_colour, face = "bold")
text_title <- element_text(size = font_size + 8, colour = text_colour, face = "bold")
theme_minimal(base_family = font_family) +
theme(plot.background = element_blank(),
# plot.background = element_rect(fill = bg_colour),
text = text_normal,
plot.title = text_title,
plot.subtitle = text_italic,
axis.title = text_normal,
axis.text = text_small_dark,
legend.title = text_small_dark,
legend.text = text_small_dark) +
theme(axis.line = element_line(colour = "grey20"),
axis.ticks = element_blank(),
legend.position = "bottom",
legend.title = element_blank(),
panel.grid = element_blank(),
strip.background = element_rect(fill = bg_colour2, colour = bg_colour2),
strip.text = text_small_dark)
}
#' @title Basic theme for 'wpa' visualisations
#'
#' @description
#' A theme function applied to 'ggplot' visualisations in 'wpa'.
#' Based on `theme_wpa()` but has no font requirements.
#'
#' @param font_size Numeric value that prescribes the base font size
#' for the plot. The text elements are defined relatively to this
#' base font size. Defaults to 12.
#'
#' @import ggplot2
#'
#' @family Themes
#'
#' @return
#' Returns a ggplot object with the applied theme.
#'
#' @export
theme_wpa_basic <- function(font_size = 12){
bg_colour <- "#FFFFFF"
bg_colour2 <- "#CCCCCC" # light grey
text_colour <- "grey40"
text_tiny_dark <- element_text(size = font_size - 4, colour = text_colour, face = "plain")
text_small_dark <- element_text(size = font_size - 2, colour = text_colour, face = "plain")
text_small_light <- element_text(size = font_size - 2, colour = "#FFFFFF", face = "plain")
text_normal <- element_text(size = font_size + 0, colour = text_colour, face = "plain")
text_italic <- element_text(size = font_size + 0, colour = text_colour, face = "italic")
text_bold <- element_text(size = font_size + 0, colour = text_colour, face = "bold")
text_title <- element_text(size = font_size + 2, colour = text_colour, face = "bold")
theme_minimal() +
theme(plot.background = element_blank(),
# plot.background = element_rect(fill = bg_colour),
text = text_normal,
plot.title = text_title,
plot.subtitle = text_normal,
plot.caption = text_tiny_dark,
axis.title = text_normal,
axis.text = text_small_dark,
legend.title = text_small_dark,
legend.text = text_small_dark) +
theme(axis.line = element_line(colour = "grey20"),
axis.ticks = element_blank(),
legend.position = "bottom",
# legend.title = element_blank(),
panel.grid = element_blank(),
strip.background = element_rect(fill = bg_colour2, colour = bg_colour2),
strip.text = text_small_dark)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/themes.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Clean subject line text prior to analysis
#'
#' @description
#' This function processes the `Subject` column in a Meeting Query by applying
#' tokenisation using`tidytext::unnest_tokens()`, and removing any stopwords
#' supplied in a data frame (using the argument `stopwords`). This is a
#' sub-function that feeds into `tm_freq()`, `tm_cooc()`, and `tm_wordcloud()`.
#' The default is to return a data frame with tokenised counts of words or
#' ngrams.
#'
#'
#' @param data A Meeting Query dataset in the form of a data frame.
#' @param token A character vector accepting either `"words"` or `"ngrams"`,
#' determining type of tokenisation to return.
#' @param stopwords A character vector OR a single-column data frame labelled
#' `'word'` containing custom stopwords to remove.
#' @param ... Additional parameters to pass to `tidytext::unnest_tokens()`.
#'
#' @import dplyr
#' @import ggplot2
#' @importFrom tidytext unnest_tokens
#'
#' @family Text-mining
#'
#' @examples
#' # words
#' tm_clean(mt_data)
#'
#' # ngrams
#' tm_clean(mt_data, token = "ngrams")
#'
#' @return
#' data frame with two columns:
#' - `line`
#' - `word`
#'
#' @export
tm_clean <- function(data,
token = "words",
stopwords = NULL,
...){
# Get a dataset with only subjects and a subject line ID
text_df <-
data %>%
select(Subject) %>%
mutate(line = 1:n(),
text = as.character(Subject)) %>%
select(line, text)
# If `stopwords` is passed as a character vector, convert to data frame
if(is.character(stopwords)){
stopwords <-
data.frame(
word = stopwords
)
}
# Expand dataset to have each word in the subject as a different observation
text_df <- text_df %>%
tidytext::unnest_tokens(
word,
text,
token = token,
...)
# Remove common English stop words (and, or, at, etc)
text_df <-
text_df %>%
dplyr::anti_join(tidytext::stop_words) %>%
suppressMessages()
# Remove WPI custom irrelevant words
if(!is.data.frame(stopwords)){
stopwords <- dplyr::tibble(word = "")
}
text_df %>%
anti_join(stopwords) %>%
suppressMessages()
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/tm_clean.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title
#' Analyse word co-occurrence in subject lines and return a network plot
#'
#' @description
#' This function generates a word co-occurrence network plot, with options to
#' return a table. This function is used within `meeting_tm_report()`.
#'
#' @author Carlos Morales <carlos.morales@@microsoft.com>
#'
#' @details
#' This function uses `tm_clean()` as the underlying data wrangling function.
#' There is an option to remove stopwords by passing a data frame into the
#' `stopwords` argument.
#'
#' @param data A Meeting Query dataset in the form of a data frame.
#' @param stopwords A character vector OR a single-column data frame labelled
#' `'word'` containing custom stopwords to remove.
#' @param seed A numeric vector to set seed for random generation.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#'
#' See `Value` for more information.
#'
#' @param lmult A multiplier to adjust the line width in the output plot.
#' Defaults to 0.05.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: 'ggplot' and 'ggraph' object. A network plot.
#' - `"table"`: data frame. A summary table.
#'
#' @import dplyr
#' @import ggplot2
#' @import ggraph
#' @importFrom igraph graph_from_data_frame
#' @importFrom tidytext unnest_tokens
#'
#' @family Text-mining
#'
#' @examples
#' \donttest{
#' # Demo using a subset of `mt_data`
#' mt_data %>%
#' dplyr::slice(1:20) %>%
#' tm_cooc(lmult = 0.01)
#' }
#'
#' @export
tm_cooc <- function(data,
stopwords = NULL,
seed = 100,
return = "plot",
lmult = 0.05){
# Clean data
text_df <- suppressMessages(tm_clean(data = data,
token = "words",
stopwords = stopwords))
# Calculate frequency of pairs
title_word_pairs <-
text_df %>%
pairwise_count(id = "line", word = "word")
# Graph networks
set.seed(seed)
p <-
title_word_pairs %>%
dplyr::top_n(500) %>%
igraph::graph_from_data_frame() %>%
ggraph::ggraph(layout = "fr") +
ggraph::geom_edge_link(aes(edge_alpha = 0.5, edge_width = n * lmult), edge_colour = "cyan4") +
ggraph::geom_node_point(size = 2) +
ggraph::geom_node_text(aes(label = name),
repel = TRUE,
point.padding = unit(0.2, "lines")) +
ggplot2::theme(panel.background = ggplot2::element_rect(fill = 'white'), legend.position = "none")
if(return == "table"){
title_word_pairs %>%
dplyr::top_n(500) %>%
as_tibble() %>%
return()
} else if(return == "plot"){
return(p)
} else {
stop("Please enter a valid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/tm_cooc.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Perform a Word or Ngram Frequency Analysis and return a Circular Bar
#' Plot
#'
#' @description
#' Generate a circular bar plot with frequency of words / ngrams.
#' This function is used within `meeting_tm_report()`.
#'
#' @details
#' This function uses `tm_clean()` as the underlying data wrangling function.
#' There is an option to remove stopwords by passing a data frame into the
#' `stopwords` argument.
#'
#' @param data A Meeting Query dataset in the form of a data frame.
#' @param token A character vector accepting either `"words"` or `"ngram"`,
#' determining type of tokenisation to return.
#' @param stopwords A character vector OR a single-column data frame labelled
#' `'word'` containing custom stopwords to remove.
#' @param keep A numeric vector specifying maximum number of words to keep.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#'
#' See `Value` for more information.
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: 'ggplot' object. A circular bar plot.
#' - `"table"`: data frame. A summary table.
#'
#' @import dplyr
#' @import ggplot2
#' @importFrom tidytext unnest_tokens
#' @importFrom stats na.omit
#'
#'
#' @examples
#' \donttest{
#' tm_freq(mt_data, token = "words")
#' tm_freq(mt_data, token = "ngrams")
#' }
#'
#' @family Text-mining
#'
#' @export
tm_freq <- function(data,
token = "words",
stopwords = NULL,
keep = 100,
return = "plot"){
# Clean data
text_df <- suppressMessages(tm_clean(data = data,
token = token,
stopwords = stopwords))
# Calculate frequency of word sand keep top 100 terms
text_count <-
text_df %>%
count(word, sort = TRUE) %>%
stats::na.omit() %>%
top_n(keep)
# Plot as a circular bar chart
# Note that id is a factor. If x is numeric, there is some space between the first bar
# `fill` in `geom_bar` add the bars with a blue color
# Limits of the plot = very important.
# The negative value controls the size of the inner circle,
# the positive one is useful to add size over each bar
# Custom the theme: no axis title and no cartesian grid
# `coord_polar` makes the coordinate polar instead of cartesian.
# `geom_text` adds the labels, using the label_data dataframe that we have created before
p <-
ggplot(text_count, aes(x=as.factor(word), y=n)) +
geom_bar(stat="identity", fill=alpha("skyblue", 0.7)) +
ylim(-100,max(text_count$n) + 10) +
theme_minimal() +
theme(
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
plot.margin = unit(rep(-1,4), "cm") # Adjust the margin to make in sort labels are not truncated!
) +
coord_polar(start = 0) +
ggrepel::geom_text_repel(
data = text_count,
aes(x=word, y=n+10, label=word),
color = "black",
fontface = "bold",
alpha = 0.6,
size = 2.5,
inherit.aes = FALSE)
if(return == "table"){
text_count %>%
as_tibble() %>%
return()
} else if(return == "plot"){
return(p)
} else {
stop("Please enter a valid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/tm_freq.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Generate a wordcloud with meeting subject lines
#'
#' @description
#' Generate a wordcloud with the meeting query.
#' This is a sub-function that feeds into `meeting_tm_report()`.
#'
#' @details
#' Uses the 'ggwordcloud' package for the underlying implementation, thus
#' returning a 'ggplot' object. Additional layers can be added onto the plot
#' using a ggplot `+` syntax.
#' The recommendation is not to return over 100 words in a word cloud.
#'
#' @details
#' This function uses `tm_clean()` as the underlying data wrangling function.
#' There is an option to remove stopwords by passing a data frame into the
#' `stopwords` argument.
#'
#' @param data A Meeting Query dataset in the form of a data frame.
#' @param stopwords A character vector OR a single-column data frame labelled
#' `'word'` containing custom stopwords to remove.
#' @param seed A numeric vector to set seed for random generation.
#' @param keep A numeric vector specifying maximum number of words to keep.
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#'
#' See `Value` for more information.
#' @param ... Additional parameters to be passed to
#' `ggwordcloud::geom_text_wordcloud()`
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: 'ggplot' object containing a word cloud.
#' - `"table"`: data frame returning the data used to generate the word cloud.
#'
#' @import dplyr
#' @examples
#' tm_wordcloud(mt_data, keep = 30)
#'
#' # Removing stopwords
#' tm_wordcloud(mt_data, keep = 30, stopwords = c("weekly", "update"))
#'
#' @family Text-mining
#'
#' @export
tm_wordcloud <- function(data,
stopwords = NULL,
seed = 100,
keep = 100,
return = "plot",
...){
set.seed(seed)
clean_data <-
suppressMessages(tm_clean(
data = data,
token = "words",
stopwords = stopwords
))
plot_data <-
clean_data %>% # Remove additional stop words
count(word, name = "freq") %>%
arrange(desc(freq))
if(nrow(plot_data) < keep){
keep <- nrow(plot_data)
}
plot_data <- plot_data %>% slice(1:keep)
if(return == "plot"){
output <-
plot_data %>%
ggplot(aes(label = word, size = freq)) +
ggwordcloud::geom_text_wordcloud(rm_outside = TRUE, ...) +
scale_size_area(max_size = 15) +
theme_minimal()
return(output)
} else if (return == "table"){
return(plot_data)
} else {
stop("Please enter a valid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/tm_wordcloud.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Row-bind an identical data frame for computing grouped totals
#'
#' @description Row-bind an identical data frame and impute a specific
#' column with the `target_value`, which defaults as "Total". The purpose of
#' this is to enable to creation of summary tables with a calculated "Total"
#' row. See example below on usage.
#'
#' @examples
#' sq_data %>%
#' totals_bind(target_col = "LevelDesignation", target_value = "Total") %>%
#' collab_sum(hrvar = "LevelDesignation", return = "table")
#'
#' @param data data frame
#' @param target_col Character value of the column in which to impute `"Total"`.
#' This is usually the intended grouping column.
#' @param target_value Character value to impute in the new data frame to
#' row-bind. Defaults to `"Total"`.
#'
#' @return
#' data frame with twice the number of rows of the input data frame, where half
#' of those rows will have the `target_col` column imputed with the value from
#' `target_value`.
#'
#' @family Support
#'
#' @export
totals_bind <- function(data, target_col, target_value = "Total"){
data %>%
dplyr::bind_rows(dplyr::mutate(., !!sym(target_col) := target_value))
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/totals_bind.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Fabricate a 'Total' HR variable
#'
#' @description Create a 'Total' column of character type comprising exactly of
#' one unique value. This is a convenience function for returning a no-HR
#' attribute view when `NULL` is supplied to the `hrvar` argument in
#' functions.
#'
#' @examples
#' # Create a visual without HR attribute breaks
#' sq_data %>%
#' totals_col() %>%
#' collab_fizz(hrvar = "Total")
#'
#' @param data data frame
#' @param total_value Character value defining the name and the value of the
#' `"Total"` column. Defaults to `"Total"`. An error is returned if an
#' existing variable has the same name as the supplied value.
#'
#' @return
#' data frame containing an additional 'Total' column on top of the input data
#' frame.
#'
#' @family Support
#'
#' @export
totals_col <- function(data, total_value = "Total"){
if(total_value %in% names(data)){
stop(paste("Column", wrap(total_value, wrapper = "`"), "already exists. Please supply a different
value to `total_value`"))
}
data %>%
dplyr::mutate(!!sym(total_value) := total_value)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/totals_col.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Reorder a value to the top of the summary table
#'
#' @description For a given data frame, reorder a row to the first row of that
#' data frame through matching a _value_ of a _variable_. The intended usage
#' of this function is to be used for reordering the "Total" row, and _not_
#' with "flat" data. This can be used in conjunction with `totals_bind()`,
#' which is used to create a "Total" row in the data.
#'
#' @examples
#' sq_data %>%
#' totals_bind(target_col = "LevelDesignation",
#' target_value = "Total") %>%
#' collab_sum(hrvar = "LevelDesignation",
#' return = "table") %>%
#' totals_reorder(target_col = "group", target_value = "Total")
#'
#' @param data Summary table in the form of a data frame.
#' @param target_col Character value of the column in which to reorder
#' @param target_value Character value of the value in `target_col` to match
#'
#' @return
#' data frame with the 'Total' row reordered to the bottom.
#'
#' @family Support
#'
#' @export
totals_reorder <- function(data, target_col, target_value = "Total"){
tc <- unique(data[[target_col]])
the_rest <- tc[tc != target_value]
order <- c(target_value, the_rest)
dplyr::slice(data, match(order, !!sym(target_col)))
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/totals_reorder.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Sankey chart of organizational movement between HR attributes and
#' missing values (outside company move) (Data Overview)
#'
#' @description
#' Creates a list of everyone at a specified start date and a specified end date
#' then aggregates up people who have moved between organizations between this
#' to points of time and visualizes the move through a sankey chart.
#'
#' Through this chart you can see:
#' - The HR attribute/orgs that have the highest move out
#' - The HR attribute/orgs that have the highest move in
#' - The number of people that do not have that HR attribute or if they are no
#' longer in the system
#'
#' @author Tannaz Sattari Tabrizi <Tannaz.Sattari@@microsoft.com>
#'
#' @param data A Person Query dataset in the form of a data frame.
#' @param start_date A start date to compare changes. See `end_date`.
#' @param end_date An end date to compare changes. See `start_date`.
#' @param hrvar HR Variable by which to compare changes between, defaults to
#' `"Organization"` but accepts any character vector, e.g.
#' `"LevelDesignation"`
#' @param mingroup Numeric value setting the privacy threshold / minimum group
#' size. Defaults to 5.
#' @param return Character vector specifying what to return, defaults to
#' `"plot"`. Valid inputs are `"plot"` and `"table"`.
#' @param NA_replacement Character replacement for NA defaults to "out of
#' company"
#'
#' @import dplyr
#'
#' @family Data Validation
#'
#' @return
#' Returns a 'NetworkD3' object by default, where 'plot' is passed in `return`.
#' When 'table' is passed, a summary table is returned as a data frame.
#'
#' @examples
#'
#' dv_data %>% track_HR_change()
#'
#' @export
track_HR_change <- function(data,
start_date = min(data$Date),
end_date = max(data$Date),
hrvar = "Organization",
mingroup = 5,
return = "plot",
NA_replacement = "Out of Company"){
## Check inputs
required_variables <- c("Date",
"PersonId",
hrvar)
## Error message if variables are not present
## Nothing happens if all present
data %>%
check_inputs(requirements = required_variables)
## Define Start and End Dates
data_start_date <- min(as.Date(data$Date,"%m/%d/%Y"))
data_end_date <- max(as.Date(data$Date,"%m/%d/%Y"))
## Validate dates
if (as.Date(end_date,"%m/%d/%Y") < data_start_date){
stop("Please enter a valid start date.")
}
if (as.Date(start_date,"%m/%d/%Y") > data_end_date ){
stop("Please enter a valid end date.")
}
## filter data to starting point
start_data <- data %>%
filter(Date == start_date) %>%
select("PersonId", hrvar) %>%
rename(group := !!sym(hrvar))
## filter data to end point
end_data <- data %>%
filter(Date == end_date) %>%
select("PersonId", hrvar) %>%
rename(pre_group := !!sym(hrvar))
## Join the data to track the changes
dt <- merge(start_data, end_data, by = "PersonId", all.x = TRUE)
# aggregate the data over different orgs
moves <-
dt %>%
group_by(pre_group, group) %>%
summarise(Employee_Count = n(), .groups = "drop") %>%
# clean the data to changes and replace NAs
mutate(group = tidyr::replace_na(group, NA_replacement),
pre_group = tidyr::replace_na(pre_group, NA_replacement)) %>%
arrange(desc(Employee_Count))
if(length(moves) == 0){
stop("No change has happened.")
}
## Save summary table to myTableReturn
myTableReturn <- moves
if(return == "table"){
return(myTableReturn)
} else if(return == "plot"){
## Plotting for sankey chart
## Set up `nodes`
group_source <- unique(moves$pre_group)
group_target <- paste0(unique(moves$group), " ")
groups <- c(group_source, group_target)
nodes_source <- tibble(name = group_source)
nodes_target <- tibble(name = group_target)
nodes <- rbind(nodes_source, nodes_target) %>% mutate(node = 0:(nrow(.) - 1))
## Set up `links`
links <-
moves %>%
mutate(group = paste0(group, " ")) %>%
select(source = "pre_group",
target = "group",
value = "Employee_Count")
nodes_source <- nodes_source %>% select(name) # Make `nodes` a single column data frame
nodes_target <- nodes_target %>% select(name) # Make `nodes` a single column data frame
links <-
links %>%
left_join(nodes %>% rename(IDsource = "node"), by = c("source" = "name")) %>%
left_join(nodes %>% rename(IDtarget = "node"), by = c("target" = "name"))
networkD3::sankeyNetwork(Links = as.data.frame(links),
Nodes = as.data.frame(nodes),
Source = 'IDsource', # Change reference to IDsource
Target = 'IDtarget', # Change reference to IDtarget
Value = 'value',
NodeID = 'name',
units="count",
sinksRight = FALSE)
} else {
stop("Please enter a valid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/track_hr_change.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Generate a time stamp
#'
#' @description
#' This function generates a time stamp of the format `'yymmdd_hhmmss'`.
#' This is a support function and is not intended for direct use.
#'
#' @family Support
#'
#' @return
#' String containing the timestamp in the format `'yymmdd_hhmmss'`.
#'
#' @export
tstamp <- function(){
stamp <- Sys.time()
stamp <- gsub(pattern = "[[:punct:]]", replacement = "", x = stamp)
stamp <- gsub(pattern = " ", replacement = "_", x = stamp)
return(stamp)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/tstamp.R
|
#' @title Replace underscore with space
#'
#' @description Convenience function to convert underscores to space
#'
#' @param x String to replace all occurrences of `_` with a single space
#'
#' @return
#' Character vector containing the modified string.
#'
#' @family Support
#'
#' @examples
#' us_to_space("Meeting_hours_with_manager_1_on_1")
#'
#' @export
us_to_space <- function(x){
gsub(pattern = "_", replacement = " ", x = x)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/us_to_space.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' Pipe operator
#'
#' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details.
#'
#' @name %>%
#' @rdname pipe
#' @keywords internal
#' @export
#' @importFrom magrittr %>%
#' @usage lhs \%>\% rhs
#' @return
#' Returns immediate object.
NULL
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/utils-pipe.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Generate a Data Validation report in HTML
#'
#' @description
#' The function generates an interactive HTML report using
#' Standard Person Query data as an input. The report contains checks on
#' Workplace Analytics query outputs to provide diagnostic information
#' for the Analyst prior to analysis.
#'
#' An additional Standard Meeting Query can be provided to perform meeting
#' subject line related checks. This is optional and the validation report can
#' be run without it.
#'
#' @details
#' For your input to `data` or `meeting_data`, please use the function
#' `wpa::import_wpa()` to import your csv query files into R. This function will
#' standardize format and prepare the data as input for this report.
#'
#' If you are passing a Ways of Working Assessment query instead of a Standard
#' Person query to the `data` argument, please also use `standardise_pq()` to
#' make the variable names consistent with a Standard Person Query.
#'
#' Since `v1.6.2`, the variable `Call_hours` is no longer a pre-requisite to run
#' this report. A note is returned in-line instead of an error if the variable
#' is not available.
#'
#' @section Checking functions within `validation_report()`:
#' - `check_query()`
#' - `flag_ch_ratio()`
#' - `hrvar_count_all()`
#' - `identify_privacythreshold()`
#' - `identify_nkw()`
#' - `identify_holidayweeks()`
#' - `subject_validate()`
#' - `identify_tenure()`
#' - `flag_outlooktime()`
#' - `identify_shifts()`
#' - `track_HR_change()`
#'
#' You can browse each individual function for details on calculations.
#'
#' @param data A Standard Person Query dataset in the form of a data frame.
#' @param meeting_data An optional Meeting Query dataset in the form of a data
#' frame.
#' @param hrvar HR Variable by which to split metrics, defaults to "Organization"
#' but accepts any character vector, e.g. "Organization"
#' @param path Pass the file path and the desired file name, _excluding the file
#' extension_.
#' @param hrvar_threshold Numeric value determining the maximum number of unique
#' values to be allowed to qualify as a HR variable. This is passed directly
#' to the `threshold` argument within `hrvar_count_all()`.
#' @param timestamp Logical vector specifying whether to include a timestamp in
#' the file name. Defaults to `TRUE`.
#'
#' @section Creating a report:
#'
#' Below is an example on how to run the report.
#'
#' ```
#' validation_report(dv_data,
#' meeting_data = mt_data,
#' hrvar = "Organization")
#' ```
#'
#'
#' @importFrom purrr map_if
#' @importFrom dplyr `%>%`
#'
#' @family Reports
#' @family Data Validation
#'
#' @inherit generate_report return
#'
#' @export
validation_report <- function(data,
meeting_data = NULL,
hrvar = "Organization",
path = "validation report",
hrvar_threshold = 150,
timestamp = TRUE){
## Create timestamped path (if applicable)
if(timestamp == TRUE){
newpath <- paste(path, wpa::tstamp())
} else {
newpath <- path
}
## Handle variable name consistency
data <- qui_stan_c(data)
data <- qui_stan_im(data)
## Dynamic: if meeting data is not available
if(is.null(meeting_data)){
subline_obj <- "[Note] Subject line analysis is unavailable as no meeting query is supplied."
subline_obj2 <- ""
} else {
subline_obj <- meeting_data %>% subject_validate(return = "text")
subline_obj2 <- meeting_data %>% subject_validate(return = "table")
}
## Dynamic: if `HireDate` is not available
if("HireDate" %in% names(data)){
tenure_obj <- data %>% identify_tenure(return = "text") %>% suppressWarnings()
tenure_obj2 <- data %>% identify_tenure(return = "plot") %>% suppressWarnings()
} else {
tenure_obj <- "[Note] Tenure analysis is unavailable as the data has no `HireDate` variable."
tenure_obj2 <- ""
}
## Dynamic: if `WorkingStartTimeSetInOutlook` and `WorkingEndTimeSetInOutlook` is not available
wktimes_var <- c("WorkingStartTimeSetInOutlook", "WorkingEndTimeSetInOutlook")
wktimes_msg <- "[Note] Outlook hours analysis is unavailable as the data does not have the following variables:"
if(all(wktimes_var %in% names(data))){
wktimes_obj <- data %>% flag_outlooktime(return = "text")
shift_obj <- data %>% identify_shifts(return = "plot")
} else {
wktimes_obj <- paste(wktimes_msg, paste(wrap(wktimes_var, "`"), collapse = ", "), collapse = "\n")
shift_obj <- paste(wktimes_msg, paste(wrap(wktimes_var, "`"), collapse = ", "), collapse = "\n")
}
## Dynamic: Track HR changes
mtry <- try(track_HR_change(data, hrvar = hrvar), silent = TRUE)
if (!inherits(mtry, "try-error")) {
trackhr_obj <- data %>% track_HR_change(hrvar = hrvar, return = "plot")
trackhr_obj2 <- data %>% track_HR_change(hrvar = hrvar, return = "table")
} else {
trackhr_obj <- "[Error!] unable to parse HR changes."
trackhr_obj2 <- ""
}
## Dynamic: create mock `Call_hours` variable
callthres_p <- NULL
callthres <- NULL
if("Call_hours" %in% names(data)){
callthres_p <- paste(
">",
data %>%
flag_extreme(
metric = "Call_hours",
threshold = 40,
person = TRUE,
return = "text"
)
)
callthres <-
paste(
">",
data %>% flag_extreme(
metric = "Call_hours",
threshold = 40,
person = FALSE,
return = "text"
)
)
} else {
callthres_p <-
"> [Note] Checks for `Call_hours` is not available due to missing variable."
callthres <- callthres_p
}
## Outputs as accessed here
## Can be data frames, plot objects, or text
output_list <-
list(read_preamble("blank.md"), # Header - Data Available
data %>% check_query(return = "text", validation = TRUE),
read_preamble("blank.md"), # Header - 1.1 Workplace Analytics Settings
read_preamble("outlook_settings_1.md"),
shift_obj, # See `identify_shifts()` dynamic treatment above
read_preamble("outlook_settings_2.md"),
paste(">", wktimes_obj),
paste(">", data %>% flag_ch_ratio(return = "text")),
read_preamble("outlook_settings_3.md"),
read_preamble("meeting_exclusions_1.md"), #item 9, Header - 1.2 Meeting Exclusions
paste(">", subline_obj),
subline_obj2,
read_preamble("meeting_exclusions_2.md"),
read_preamble("organizational_data_quality.md"), #13, Header - 2. Organizational Data Quality
read_preamble("attributes_available.md"),#14
data %>% hrvar_count_all(return = "table", threshold = hrvar_threshold),
read_preamble("groups_under_privacy_threshold_1.md"), #16, Header - 2.2 Groups under Privacy Threshold
paste(">", data %>% identify_privacythreshold(return="text")),
read_preamble("groups_under_privacy_threshold_2.md"),
data %>% identify_privacythreshold(return="table"),
read_preamble("distribution_employees_key_attributes.md"), #20, Header - 2.3 Distribution employees key attributes
data %>% hrvar_count(hrvar = hrvar, return = "plot"),
data %>% hrvar_count(hrvar = hrvar, return = "table"),
read_preamble("updates_organizational_data.md"), #23, Header - 2.4 Updates to Organizational Data
read_preamble("blank.md"), #placeholder for track_HR_change message obj,
trackhr_obj,
trackhr_obj2,
read_preamble("quality_tenure_data.md"), #27, Header - 2.5 Quality Tenure Data
paste(">", tenure_obj), # Text
tenure_obj2, # Plot
read_preamble("m365_data_quality.md"), #30, Header - 3. M365 Data Quality
read_preamble("population_over_time.md"), #Header - 3.1
data %>% hr_trend(return = "plot"),
read_preamble("nonknowledge_workers.md"), #33, Header - 3.2 Non-knowledge workers
paste(">", data %>% identify_nkw(return = "text")),
data %>% identify_nkw(return = "data_summary"),
read_preamble("holiday_weeks_1.md"), #36, Header - 3.3 Company Holiday weeks
paste(">", data %>% identify_holidayweeks(return = "text")),
read_preamble("holiday_weeks_2.md"),
data %>% identify_holidayweeks(return = "plot"),
read_preamble("inactive_weeks_1.md"), #40, Header - 3.4 Inactive weeks
paste(">", data %>% identify_inactiveweeks(return = "text")),
read_preamble("inactive_weeks_2.md"),
read_preamble("extreme_values.md"), #43, Header - 3.5 Extreme values
paste(">",data %>% flag_extreme(metric = "Email_hours", threshold = 80, person = TRUE, return = "text")),
paste(">",data %>% flag_extreme(metric = "Email_hours", threshold = 80, person = FALSE, return = "text")),
paste(">",data %>% flag_extreme(metric = "Meeting_hours", threshold = 80, person = TRUE, return = "text")),
paste(">",data %>% flag_extreme(metric = "Meeting_hours", threshold = 80, person = FALSE, return = "text")),
callthres_p,
callthres,
paste(">",data %>% flag_extreme(metric = "Instant_Message_hours", threshold = 40, person = TRUE, return = "text")),
paste(">",data %>% flag_extreme(metric = "Instant_Message_hours", threshold = 40, person = FALSE, return = "text")),
paste(">",data %>% flag_extreme(metric = "Conflicting_meeting_hours", threshold = 70, person = TRUE, return = "text")),
paste(">",data %>% flag_extreme(metric = "Conflicting_meeting_hours", threshold = 70, person = FALSE, return = "text")),
paste(">",data %>% flag_extreme(metric = "Collaboration_hours", threshold = 0, person = TRUE, mode = "equal", return = "text")),
paste(">",data %>% flag_extreme(metric = "Collaboration_hours", threshold = 0, person = FALSE, mode = "equal", return = "text"))
) %>%
purrr::map_if(is.data.frame, create_dt, rounding = 0) %>%
purrr::map_if(is.character, md2html)
## Title of the outputs
title_list <-
c("Data Available",
"Query Check",
"1. Workplace Analytics Settings",
"1.1 Outlook Settings",
"",
"",
"",
"",
"",
"1.2 Meeting Exclusion Rules",
"",
"",
"",
"2. Organizational Data Quality",
"2.1 Attributes Available",
"",
"2.2 Groups Under Privacy Threshold",
"",
"",
"",
"2.3 Distribution of Employees in Key Attributes",
"",
"",
"2.4 Updates to Organizational Data",
"",
"",
"",
"2.5 Quality of Tenure Data",
"",
"",
"3. M365 Data Quality",
"3.1 Population Over Time",
"",
"3.2 Non-knowledge Workers",
"",
"",
"3.3 Company Holiday Weeks",
"",
"",
"",
"3.4 Inactive Weeks",
"",
"",
"3.5 Extreme Values",
"3.5.1 Extreme values: Email",
"",
"3.5.2 Extreme values: Meeting",
"",
"3.5.3 Extreme values: Calls",
"",
"3.5.4 Extreme values: IM",
"",
"3.5.5 Extreme values: Conflicting Meetings",
"",
"3.5.6 Extreme values: Zero collaboration",
""
)
# Set header levels
n_title <- length(title_list)
levels_list <- rep(4, n_title)
levels_list[c(1, 3, 14, 31)] <- 2 # Section header
generate_report(title = "Data Validation Report",
filename = newpath,
outputs = output_list,
titles = title_list,
subheaders = rep("", n_title),
echos = rep(FALSE, n_title),
levels = levels_list,
theme = "cosmo",
preamble = read_preamble("validation_report.md")) # See inst/preamble/validation_report.md
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/validation_report.R
|
#' @title Generate a Wellbeing Report in HTML
#'
#' @description
#' `r lifecycle::badge('experimental')`
#'
#' Generate a static HTML report on wellbeing, taking a custom Wellbeing Query
#' and an Hourly Collaboration query as inputs. See `Required metrics` section
#' for more details on the required inputs for the Wellbeing Query. Note that
#' this function is currently still in experimental/development stage and may
#' experience changes in the near term.
#'
#' @param wbq Data frame. A custom Wellbeing Query dataset based on the Person
#' Query. If certain metrics are missing from the Wellbeing / Person Query,
#' the relevant visual will show up with an indicative message.
#' @param hcq Data frame. An Hourly Collaboration Query dataset.
#' @param hrvar String specifying HR attribute to cut by archetypes. Defaults to
#' `Organization`.
#' @param mingroup Numeric value setting the privacy threshold / minimum group
#' size. Defaults to 5.
#' @param start_hour A character vector specifying starting hours, e.g.
#' `"0900"`. Note that this currently only supports **hourly** increments. If
#' the official hours specifying checking in and 9 AM and checking out at 5
#' PM, then `"0900"` should be supplied here.
#' @param end_hour A character vector specifying starting hours, e.g. `"1700"`.
#' Note that this currently only supports **hourly** increments. If the
#' official hours specifying checking in and 9 AM and checking out at 5 PM,
#' then `"1700"` should be supplied here.
#' @param path Pass the file path and the desired file name, _excluding the file
#' extension_. Defaults to `"wellbeing_report"`.
#'
#' @section Required metrics:
#' A full list of the required metrics are as follows:
#' - `Urgent_meeting_hours`
#' - `IMs_sent_other_level`
#' - `IMs_sent_same_level`
#' - `Emails_sent_other_level`
#' - `Emails_sent_same_level`
#' - `Emails_sent`
#' - `IMs_sent`
#' - `Meeting_hours_intimate_group`
#' - `Meeting_hours_1on1`
#' - `Urgent_email_hours`
#' - `Unscheduled_call_hours`
#' - `Meeting_hours`
#' - `Instant_Message_hours`
#' - `Email_hours`
#' - `Total_focus_hours`
#' - `Weekend_IMs_sent`
#' - `Weekend_emails_sent`
#' - `After_hours_collaboration_hours`
#' - `After_hours_meeting_hours`
#' - `After_hours_instant_messages`
#' - `After_hours_in_unscheduled_calls`
#' - `After_hours_email_hours`
#' - `Collaboration_hours`
#' - `Workweek_span`
#'
#'
#' @export
wellbeing_report <- function(wbq,
hcq,
hrvar = "Organization",
mingroup = 5,
start_hour = "0900",
end_hour = "1700",
path = "wellbeing_report"
){
## Check if dependencies are installed
check_pkg_installed(pkgname = "flexdashboard")
## Generate report from RMarkdown
generate_report2(
wbq = wbq,
hcq = hcq,
hrvar = hrvar,
mingroup = mingroup,
output_file = paste0(path, ".html"),
report_title = "Org Insights | Employee Wellbeing Report",
rmd_dir = system.file("rmd_template/wellbeing/wellbeing_report.rmd", package = "wpa"),
output_format =
flexdashboard::flex_dashboard(orientation = "columns",
vertical_layout = "fill",
css = system.file("rmd_template/wellbeing/custom.css", package = "wpa")),
# Additional arguments to param
start_hour = start_hour,
end_hour = end_hour
)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/wellbeing_report.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Distribution of Work Week Span as a 100% stacked bar
#'
#' @description
#' Analyze Work Week Span distribution.
#' Returns a stacked bar plot by default.
#' Additional options available to return a table with distribution elements.
#'
#' @inheritParams create_dist
#' @inherit create_dist return
#'
#' @family Visualization
#' @family Workweek Span
#'
#' @examples
#' # Return plot
#' workloads_dist(sq_data, hrvar = "Organization", return = "plot")
#'
#' # Return a summary table
#' workloads_dist(sq_data, hrvar = "Organization", return = "table")
#'
#' @export
workloads_dist <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot",
cut = c(15, 30, 45)) {
## Inherit arguments
create_dist(data = data,
metric = "Workweek_span",
hrvar = hrvar,
mingroup = mingroup,
return = return,
cut = cut)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/workloads_dist.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Distribution of Work Week Span (Fizzy Drink plot)
#'
#' @description
#' Analyze Work Week Span distribution, and returns
#' a 'fizzy' scatter plot by default.
#' Additional options available to return a table with distribution elements.
#'
#' @inheritParams create_fizz
#' @inherit create_fizz return
#'
#' @family Visualization
#' @family Workweek Span
#'
#' @examples
#' # Return plot
#' workloads_fizz(sq_data, hrvar = "Organization", return = "plot")
#'
#' # Return summary table
#' workloads_fizz(sq_data, hrvar = "Organization", return = "table")
#'
#' @export
workloads_fizz <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot"){
create_fizz(data = data,
metric = "Workweek_span",
hrvar = hrvar,
mingroup = mingroup,
return = return)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/workloads_fizz.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Workloads Time Trend - Line Chart
#'
#' @description
#' Provides a week by week view of 'Work Week Span', visualised as line charts.
#' By default returns a line chart for collaboration hours,
#' with a separate panel per value in the HR attribute.
#' Additional options available to return a summary table.
#'
#' @inheritParams create_line
#' @inherit create_line return
#'
#' @family Visualization
#' @family Workweek Span
#'
#' @examples
#' # Return a line plot
#' workloads_line(sq_data, hrvar = "LevelDesignation")
#'
#' # Return summary table
#' workloads_line(sq_data, hrvar = "LevelDesignation", return = "table")
#'
#' @export
workloads_line <- function(data,
hrvar = "Organization",
mingroup=5,
return = "plot"){
## Inherit arguments
create_line(data = data,
metric = "Workweek_span",
hrvar = hrvar,
mingroup = mingroup,
return = return)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/workloads_line.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Rank all groups across HR attributes for Work Week Span
#'
#' @description
#' This function scans a standard query output for groups with high levels of
#' Work Week Span. Returns a plot by default, with an option to return a table
#' with a all of groups (across multiple HR attributes) ranked by work week
#' span.
#'
#' @details
#' Uses the metric `Workweek_span`.
#' See `create_rank()` for applying the same analysis to a different metric.
#'
#' @inheritParams create_rank
#' @inherit create_rank return
#'
#' @family Visualization
#' @family Workweek Span
#'
#' @examples
#' # Return rank table
#' workloads_rank(
#' data = sq_data,
#' return = "table"
#' )
#'
#' # Return plot
#' workloads_rank(
#' data = sq_data,
#' return = "plot"
#' )
#'
#' @export
workloads_rank <- function(data,
hrvar = extract_hr(data),
mingroup = 5,
mode = "simple",
plot_mode = 1,
return = "table"){
data %>%
create_rank(metric = "Workweek_span",
hrvar = hrvar,
mingroup = mingroup,
mode = mode,
plot_mode = plot_mode,
return = return)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/workloads_rank.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Work Week Span Summary
#'
#' @description
#' Provides an overview analysis of 'Work Week Span'.
#' Returns a bar plot showing average weekly utilization hours by default.
#' Additional options available to return a summary table.
#'
#' @inheritParams create_bar
#' @inherit create_bar return
#'
#' @family Visualization
#' @family Workweek Span
#'
#'
#' @examples
#' # Return a ggplot bar chart
#' workloads_summary(sq_data, hrvar = "LevelDesignation")
#'
#' # Return a summary table
#' workloads_summary(sq_data, hrvar = "LevelDesignation", return = "table")
#' @export
workloads_summary <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot"){
create_bar(data = data,
hrvar = hrvar,
mingroup = mingroup,
metric = "Workweek_span",
return = return,
bar_colour = "darkblue")
}
#' @rdname workloads_summary
#' @export
workloads_sum <- workloads_summary
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/workloads_summary.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Work Week Span Time Trend
#'
#' @description
#' Provides a week by week view of Work Week Span.
#' By default returns a week by week heatmap, highlighting the points in time
#' with most activity. Additional options available to return a summary table.
#'
#' @details
#' Uses the metric `Workweek_span`.
#'
#' @inheritParams create_trend
#' @inherit create_trend return
#'
#' @family Visualization
#' @family Workweek Span
#'
#' @examples
#' # Run plot
#' workloads_trend(sq_data)
#'
#' # Run table
#' workloads_trend(sq_data, hrvar = "LevelDesignation", return = "table")
#'
#'
#' @export
workloads_trend <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot"){
create_trend(data,
metric = "Workweek_span",
hrvar = hrvar,
mingroup = mingroup,
return = return)
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/workloads_trend.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Create an area plot of emails and IMs by hour of the day
#'
#' @description
#' Uses the Hourly Collaboration query to produce an area plot of
#' Emails sent and IMs sent attended by hour of the day.
#'
#' @param data A data frame containing data from the Hourly Collaboration query.
#'
#' @param hrvar HR Variable by which to split metrics. Accepts a character
#' vector, defaults to `"Organization"` but accepts any character vector, e.g.
#' `"LevelDesignation"`
#'
#' @param mingroup Numeric value setting the privacy threshold / minimum group
#' size, defaults to 5.
#'
#' @param signals Character vector to specify which collaboration metrics to
#' use:
#' - a combination of signals, such as `c("email", "IM")` (default)
#' - `"email"` for emails only
#' - `"IM"` for Teams messages only
#' - `"unscheduled_calls"` for Unscheduled Calls only
#' - `"meetings"` for Meetings only
#'
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"table"`
#'
#' See `Value` for more information.
#'
#' @param values Character vector to specify whether to return percentages
#' or absolute values in "data" and "plot". Valid values are:
#' - `"percent"`: percentage of signals divided by total signals (default)
#' - `"abs"`: absolute count of signals
#'
#' @param start_hour A character vector specifying starting hours,
#' e.g. "0900"
#'
#' @param end_hour A character vector specifying starting hours,
#' e.g. "1700"
#'
#' @return
#' A different output is returned depending on the value passed to the `return`
#' argument:
#' - `"plot"`: ggplot object. An overlapping area plot (default).
#' - `"table"`: data frame. A summary table.
#'
#' @import dplyr
#' @import tidyselect
#' @import ggplot2
#' @importFrom tidyr replace_na
#'
#' @family Visualization
#' @family Working Patterns
#'
#' @examples
#'
#' # Create a sample small dataset
#' orgs <- c("Customer Service", "Financial Planning", "Biz Dev")
#' em_data <- em_data[em_data$Organization %in% orgs, ]
#'
#' # Return visualization of percentage distribution
#' workpatterns_area(em_data, return = "plot", values = "percent")
#'
#' # Return visualization of absolute values
#' \donttest{
#' workpatterns_area(em_data, return = "plot", values = "abs")
#' }
#'
#' # Return summary table
#' \donttest{
#' workpatterns_area(em_data, return = "table")
#' }
#'
#' @family Working Patterns
#'
#' @export
workpatterns_area <- function(data,
hrvar = "Organization",
mingroup = 5,
signals = c("email", "IM"),
return = "plot",
values = "percent",
start_hour = "0900",
end_hour = "1700"){
## Remove case-sensitivity for signals
signals <- tolower(signals)
## Text replacement only for allowed values
if(any(signals %in% c("email", "im", "unscheduled_calls", "meetings"))){
signal_set <- gsub(pattern = "email", replacement = "Emails_sent", x = signals) # case-sensitive
signal_set <- gsub(pattern = "im", replacement = "IMs_sent", x = signal_set)
signal_set <- gsub(pattern = "unscheduled_calls", replacement = "Unscheduled_calls", x = signal_set)
signal_set <- gsub(pattern = "meetings", replacement = "Meetings", x = signal_set)
total_signal_set <- paste0(signal_set, "_total")
search_set <- paste(paste0("^", signal_set, "_"), collapse = "|")
} else {
stop("Invalid input for `signals`.")
}
## Get list of variable names
## Size equivalent to size of `signal_set`
list_signal_set <-
signal_set %>%
purrr::map(function(signal_text){
names(data)[grep(pattern = signal_text, x = names(data))]
}) %>%
setNames(nm = total_signal_set) # Use total signals set
## Convert as vector
input_var <- unlist(list_signal_set) %>% as.character()
## Date range data frame
myPeriod <- extract_date_range(data)
## Average signals sent by Person
signals_df <-
data %>%
select(PersonId, hrvar, all_of(input_var)) %>%
rename(group = !!sym(hrvar)) %>%
group_by(PersonId, group) %>%
summarise_all(~mean(.)) %>%
ungroup() %>%
left_join(data %>%
rename(group = !!sym(hrvar)) %>%
group_by(group) %>%
summarise(Employee_Count = n_distinct(PersonId)),
by = "group") %>%
filter(Employee_Count >= mingroup)
## Loop and create totals
ptn_data_norm <- signals_df
for(i in 1:length(list_signal_set)){
## Name of signal
sig_name <- names(list_signal_set)[i]
sig_name_all <- list_signal_set[[i]] # individual var names
ptn_data_norm <-
ptn_data_norm %>%
mutate(!!sym(sig_name) := select(., all_of(sig_name_all)) %>% apply(1, sum)) %>%
mutate_at(vars(sig_name_all), ~./ !!sym(sig_name))
}
## Normalised pattern data
ptn_data_norm <-
ptn_data_norm %>%
select(PersonId, group, all_of(input_var)) %>%
mutate(across(where(is.numeric), ~tidyr::replace_na(., 0))) # Replace NAs with 0s
# Percentage vs Absolutes
if(values == "percent"){
# Use normalised data
ptn_data_final <- ptn_data_norm
abs_true <- FALSE
} else if(values == "abs"){
# Use data with direct person-average
ptn_data_final <- signals_df
abs_true <- TRUE
} else {
stop("Invalid `values` input. Please either input 'percent' or 'abs'.")
}
## Create summary table
summary_data <-
ptn_data_final %>%
group_by(group) %>%
summarise_at(vars(input_var), ~mean(.)) %>%
gather(Signals, Value, -group) %>%
mutate(Hours = sub(pattern = search_set, replacement = "", x = Signals)) %>%
mutate(Hours = sub(pattern = "_.+", replacement = "", x = Hours)) %>%
mutate(Hours = as.numeric(Hours)) %>%
mutate(Signals = sub(pattern = "_\\d.+", replacement = "", x = Signals)) %>%
spread(Signals, Value)
## Return
if(return == "data"){
return(ptn_data_final)
} else if(return == "plot"){
start_line <- as.numeric(gsub(pattern = "0", replacement = "", x = start_hour))
end_line <- as.numeric(gsub(pattern = "0", replacement = "", x = end_hour))
plot <-
summary_data %>%
mutate_at(vars(group), ~as.factor(.)) %>%
gather(Signals, Value, -group, -Hours) %>%
ggplot(aes(x = Hours, y = Value, colour = Signals)) +
geom_line(size = 1) +
geom_area(aes(fill = Signals), alpha = 0.2, position = 'identity') +
geom_vline(xintercept = c(start_line, end_line), linetype="dotted") +
scale_x_continuous(labels = pad2) +
facet_wrap(.~group) +
theme_wpa_basic() +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
ggtitle(label = "Distribution of collaboration activities\n by hour of day",
subtitle = paste("By", camel_clean(hrvar))) +
labs(caption = paste("Data from week of", myPeriod$Start, "to week of", myPeriod$End)) +
{if (abs_true) ylab(paste("Collaboration activity\n(absolute)"))
else ylab(paste("Collaboration activity\n(percentage of daily total)"))
}
return(plot)
} else if(return == "table"){
## Count table
count_tb <-
ptn_data_final %>%
group_by(group) %>%
summarise(n = n_distinct(PersonId))
summary_data %>%
left_join(count_tb, by = "group") %>%
return()
} else {
stop("Invalid input for `return`.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/workpatterns_area.R
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
#' @title Classify working pattern personas using a rule based algorithm
#'
#' @description `r lifecycle::badge('experimental')`
#'
#' Apply a rule based algorithm to emails or instant messages sent by hour of
#' day. Uses a binary week-based ('bw') method by default, with options to use
#' the the person-average volume-based ('pav') method.
#'
#' @author Ainize Cidoncha <ainize.cidoncha@@microsoft.com>
#' @author Carlos Morales Torrado <carlos.morales@@microsoft.com>
#' @author Martin Chan <martin.chan@@microsoft.com>
#'
#' @details
#' The working patterns archetypes are a set of segments created based on the
#' aggregated hourly activity of employees. A motivation of creating these
#' archetypes is to capture the diversity in working patterns, where for
#' instance employees may choose to take multiple or extended breaks throughout
#' the day, or choose to start or end earlier/later than their standard working
#' hours. Two methods have been developed to capture the different working
#' patterns.
#'
#' This function is a wrapper around `workpatterns_classify_bw()` and
#' `workpatterns_classify_pav()`, and calls each function depending on what is
#' supplied to the `method` argument. Both methods implement a rule-based
#' classification of either **person-weeks** or **persons** that pull apart
#' different working patterns.
#'
#' See individual sections below for details on the two different
#' implementations.
#'
#' @section Binary Week method:
#'
#' This method classifies each **person-week** into one of the eight
#' archetypes:
#' - **0 Low Activity (< 3 hours on)**: fewer than 3 hours of active hours
#' - **1.1 Standard continuous (expected schedule)**: active hours equal to
#' _expected hours_, with all activity confined within the expected start and
#' end time
#' - **1.2 Standard continuous (shifted schedule)**: active hours equal to
#' _expected hours_, with activity occurring beyond either the expected start
#' or end time.
#' - **2.1 Standard flexible (expected schedule)**: active hours less than or
#' equal to _expected hours_, with all activity confined within the expected
#' start and end time
#' - **2.2 Standard flexible (shifted schedule)**: active hours less than or
#' equal to _expected hours_, with activity occurring beyond either the
#' expected start or end time.
#' - **3 Long flexible workday**: number of active hours exceed _expected
#' hours_, with breaks occurring throughout
#' - **4 Long continuous workday**: number of active hours exceed _expected
#' hours_, with activity happening in a continuous block (no breaks)
#' - **5 Always on (13h+)**: number of active hours greater than or equal to
#' 13
#'
#' _Standard_ here denotes the behaviour of not exhibiting total number of
#' active hours which exceed the expected total number of hours, as supplied by
#' `exp_hours`. _Continuous_ refers to the behaviour of _not_ taking breaks,
#' i.e. no inactive hours between the first and last active hours of the day,
#' where _flexible_ refers to the contrary.
#'
#' This is the recommended method over `pav` for several reasons:
#' 1. `bw` ignores _volume effects_, where activity volume can still bias the
#' results towards the 'standard working hours'.
#' 2. It captures the intuition that each individual can have 'light' and
#' 'heavy' weeks with respect to workload.
#'
#' The notion of 'breaks' in the 'binary-week' method is best understood as
#' 'recurring disconnection time'. This denotes an hourly block where there is
#' consistently no activity occurring throughout the week. Note that this
#' applies a stricter criterion compared to the common definition of a break,
#' which is simply a time interval where no active work is being done, and thus
#' the more specific terminology 'recurring disconnection time' is preferred.
#'
#' In the standard plot output, the archetypes have been abbreviated to show the
#' following:
#' - **Low Activity** - archetype 0
#' - **Standard** - archetypes 1.1 and 1.2
#' - **Flexible** - archetypes 2.1 and 2.2
#' - **Long continuous** - archetype 4
#' - **Long flexible** - archetype 3
#' - **Always On** - archetype 5
#'
#' @section Person Average method:
#'
#' This method classifies each **person** (based on unique `PersonId`) into
#' one of the six archetypes:
#' - **Absent**: Fewer than 10 signals over the week.
#'
#' - **Extended Hours - Morning:** 15%+ of collaboration before start hours and
#' less than 70% within standard hours, and less than 15% of collaboration after
#' end hours
#'
#' - **Extended Hours - Evening**: Less than 15% of collaboration before start
#' hours and less than 70% within standard hours, and 15%+ of collaboration
#' after end hours
#'
#' - **Overnight workers**: less than 30% of collaboration happens within
#' standard hours
#'
#' - **Standard Hours**: over 70% of collaboration within standard hours
#'
#' - **Always On**: over 15% of collaboration happens before starting hour and
#' end hour (both conditions must satisfy) and less than 70% of collaboration
#' within standard hours
#'
#'
#' @section Flexibility Index: The Working Patterns archetypes as calculated
#' using the binary-week method shares many similarities with the Flexibility
#' Index (see `flex_index()`):
#'
#' - Both are computed directly from the Hourly Collaboration Flexible Query.
#' - Both apply the same binary conversion of activity on the signals from the
#' Hourly Collaboration Flexible Query.
#'
#'
#' @param data A data frame containing data from the Hourly Collaboration query.
#'
#' @param hrvar A string specifying the HR attribute to cut the data by.
#' Defaults to `NULL`. This only affects the function when `"table"` is
#' returned, and is only applicable for `method = "bw"`.
#'
#' @param return String specifying what to return. This must be one of the
#' following strings:
#' - `"plot"`
#' - `"data"`
#' - `"table"`
#' - `"plot-area"`
#' - `"plot-hrvar"` (only for `bw` method)
#' - `"plot-dist"` (only for `bw` method)
#'
#' See `Value` for more information.
#'
#' @param method String to pass through specifying which method to use for
#' classification. By default, a binary week-based (`bw`) method is used, with
#' options to use the the person-average volume-based (`pav`) method.
#'
#' @param values Only valid if using `pav` method. Character vector to specify
#' whether to return percentages or absolute values in `"data"` and `"plot"`.
#' Valid values are `"percent"` (default) and `"abs"`.
#'
#' @param signals Character vector to specify which collaboration metrics to
#' use:
#' - `"email"` (default) for emails only
#' - `"IM"` for Teams messages only
#' - `"unscheduled_calls"` for Unscheduled Calls only
#' - `"meetings"` for Meetings only
#' - or a combination of signals, such as `c("email", "IM")`
#'
#' @param start_hour A character vector specifying starting hours, e.g.
#' `"0900"`. Note that this currently only supports **hourly** increments. If
#' the official hours specifying checking in and 9 AM and checking out at 5
#' PM, then `"0900"` should be supplied here.
#' @param end_hour A character vector specifying starting hours, e.g. `"1700"`.
#' Note that this currently only supports **hourly** increments. If the
#' official hours specifying checking in and 9 AM and checking out at 5 PM,
#' then `"1700"` should be supplied here.
#'
#' @param exp_hours Numeric value representing the number of hours the
#' population is expected to be active for throughout the workday. By default,
#' this uses the difference between `end_hour` and `start_hour`. Only
#' applicable with the 'bw' method.
#'
#' @param mingroup Numeric value setting the privacy threshold / minimum group
#' size. Defaults to 5.
#'
#' @param active_threshold A numeric value specifying the minimum number of
#' signals to be greater than in order to qualify as _active_. Defaults to 0.
#' Only applicable for the binary-week method.
#'
#' @import dplyr
#' @import tidyselect
#' @import ggplot2
#'
#' @return Character vector to specify what to return. Valid options
#' include:
#' - `"plot"`: ggplot object. With the `bw` method, this returns a grid
#' showing the distribution of archetypes by 'breaks' and number of active
#' hours (default). With the `pav` method, this returns a faceted bar plot
#' which shows the percentage of signals sent in each hour, with each facet
#' representing an archetype.
#' - `"data"`: data frame. The raw data with the classified archetypes.
#' - `"table"`: data frame. A summary table of the archetypes.
#' - `"plot-area"`: ggplot object. With the `bw` method, this returns an area
#' plot of the percentages of archetypes shown over time. With the `pav`
#' method, this returns an area chart which shows the percentage of signals
#' sent in each hour, with each line representing an archetype.
#' - `"plot-hrvar"`: ggplot object. A bar plot showing the count of archetypes,
#' faceted by the supplied HR attribute. This is only available for the `bw`
#' method.
#' - `"plot-dist"`: returns a heatmap plot of signal distribution by hour and
#' archetypes. This is only available for the `bw` method.
#'
#' @examples
#' \donttest{
#' # Returns a plot by default
#' em_data %>% workpatterns_classify(method = "bw")
#'
#' # Return an area plot
#' # With custom expected hours
#' em_data %>%
#' workpatterns_classify(
#' method = "bw",
#' return = "plot-area",
#' exp_hours = 7
#' )
#'
#' em_data %>% workpatterns_classify(method = "bw", return = "table")
#'
#' em_data %>% workpatterns_classify(method = "pav")
#'
#' em_data %>% workpatterns_classify(method = "pav", return = "plot-area")
#'
#' }
#'
#' @family Clustering
#' @family Working Patterns
#'
#' @export
workpatterns_classify <- function(data,
hrvar = "Organization",
values = "percent",
signals = c("email", "IM"),
start_hour = "0900",
end_hour = "1700",
exp_hours = NULL,
mingroup = 5,
active_threshold = 0,
method = "bw",
return = "plot"){
# Test the format of `start_hour` and `end_hour` --------------------------
test_hour <- function(x){
if(nchar(x) != 4){
stop("Input to `start_hour` or `end_hour` must be of the form 'hhmm'.")
} else if(substr(x, start = 3, stop = 4) != "00"){
stop("Input to `start_hour` or `end_hour` must be of the form 'hhmm'. ",
"Only whole hour increments are allowed.")
}
}
test_hour(start_hour)
test_hour(end_hour)
# Method flow -------------------------------------------------------------
if(method == "bw"){
workpatterns_classify_bw(data = data,
hrvar = hrvar,
signals = signals,
start_hour = start_hour,
end_hour = end_hour,
exp_hours = exp_hours,
mingroup = mingroup,
active_threshold = active_threshold,
return = return)
} else if(method == "pav"){
workpatterns_classify_pav(data = data,
values = values,
signals = signals,
start_hour = start_hour,
end_hour = end_hour,
return = return)
} else {
stop("Invalid method: please check input for `method`")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wpa/R/workpatterns_classify.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.