R/behavioral_plot.R

Defines functions behavioral_plot

Documented in behavioral_plot

#' Functions that returns interactive plot enabling the user to see counts of behavioral questions data
#'
#' @param df
#'
#' @return
#' @export
#'
#' @examples
#' behavioral_plot(survey_data)
behavioral_plot <- function(df)
{
  df <- df %>%
    dplyr::select(behavior_a_1:behavior_a_14 )%>%
    haven::as_factor()


  labs <- sjlabelled::get_label(df) %>%
    tibble::as_tibble() %>%
    dplyr::mutate(value1 = stringr::str_trim(stringr::str_split_fixed(value, "-", n=2)[,2]))


  names(df) <- labs$value1


  behavior_plot <- df  %>%
    tidyr::pivot_longer(1:14 , names_to = "var", values_to = "value") %>%
    dplyr::group_by(var,value) %>%
    dplyr::summarise(count = dplyr::n()) %>%
    dplyr::ungroup() %>%
    dplyr::mutate(value = as.character(value)) %>%
    dplyr::mutate(value = ifelse(is.na(value),
                                 "Not applicable" , ifelse(value=="I’m not sure", "Im not sure" ,value ))) %>%
    tidyr::pivot_wider(names_from = value , values_from = count)

  plot2 <- plotly::plot_ly(autosize = F,
                           width = 900,
                           height = 900,
                           behavior_plot,x = ~var, y = ~`Not applicable`, type = 'bar',name= 'Not applicable') %>%
    plotly::add_trace(y = ~`Im not sure`, name = 'I’m not sure') %>%
    plotly::add_trace(y = ~`Very unsuccessful`, name = 'Very unsuccessful')%>%
    plotly::add_trace(y = ~`Somewhat unsuccessful`, name = 'Somewhat unsuccessful') %>%
    plotly::add_trace(y = ~`Somewhat successful`, name = 'Somewhat successful') %>%
    plotly::add_trace(y = ~`Very successful`, name = 'Very successful')%>%
    plotly::layout(yaxis = list(title = 'Count'),xaxis = list(title = ""), barmode = 'stack')

  return(plot2)


}
popiela/homework documentation built on Jan. 17, 2021, 1:22 a.m.