Data & Functions
Likert plot


Data


We load the packages we will use :

# Libraries
library(dplyr)
library(expss) # for apply_labels


We create a database :

# Create data
sample_prob <- function(n){
  x <- sample(1:100,n)
  return(x/sum(x))
}

set.seed(1806)
n <- 11

dataset <- data.frame(
  question1 = factor(sample(0:(n-1), size=500, replace=T, prob = sample_prob(n))),
  question2 = factor(sample(0:(n-1), size=500, replace=T, prob = sample_prob(n))),
  question3 = factor(sample(0:(n-1), size=500, replace=T, prob = sample_prob(n))), 
  group = factor(sample(c("group1", "group2"), size=500, replace=T))) %>%
  apply_labels(
    question1 = "Voici un très long ou très long énoncé pour la question 1", 
    question2 = "Voici un très long ou très long énoncé pour la question 2", 
    question3 = "Voici un très long ou très long énoncé pour la question 3")



#Head of dataset
knitr::kable(head(dataset,8), align = "l")
question1 question2 question3 group
1 2 9 group2
9 3 0 group1
1 5 5 group1
2 8 10 group2
2 10 7 group1
1 8 7 group2
5 7 3 group2
7 3 4 group1



likert package


Likert is a R package designed to help analyzing and visualizing Likert type items. It has been developped by Jason Bryer and Kim Speerschneider.

likert(
items, Data frame containing the likert based items. The variables in the data frame should be factors
summary, A pre-summarized data frame
grouping = NULL, Should the results be summarized by the given grouping variable (optional)
factors = NULL, A vector with length(factors) == ncol(items) defining which factor each column belongs to. The values correspond to the factor label.
importance = FALSE, Data frame of the same dimensions as items containing an importance rating for each item
nlevels = length(levels(items[, 1])), Number of possible levels. Only necessary if there are missing levels
)

Other functions used


# function to get labels et set the width 
get_label_df <- function(dataset, wrap=NULL){
  vect_label <- NULL
  for(i in names(dataset)){
    label <- attr(dataset[, i], "label")
    if(is.null(label)) label <- i
    vect_label <- c(vect_label, label)
  }
  if(!is.null(wrap)){
    vect_label <- vect_label %>% str_wrap(20)
  }
  names(vect_label) <- names(dataset)
  return(vect_label)
}


# function to get order of items in the likert plot
get_order <- function(likert_obj){
  n_rep <- ncol(likert_obj$results)-1
  tmp <- likert_obj$results[, c(1, (round(n_rep/2)+2):(n_rep+1))]
  tmp$order <- apply(tmp[, -1], 1, sum)
  order <- tmp$Item[order(tmp$order)]
  return(order)
}



Contact

This document is a work of the statistics team in the Biostatistics and Medical Information Department at Saint-Louis Hospital in Paris (SBIM).
Based on The R Graph Gallery by Yan Holtz.