Search code examples
rlikert

Nice but plain text table for likert scale data in R


I have likert scale data. I want to display them in an easy (for none-R-users) reading way. Important is that it need to be plain text on the console. No graphics or things like the likert package offers. It not have to be a table() but it should look like a table - no matter what magic R construct is behind it.

This table is just for a first view when beginning with exploring the dataset.

This is the example data

> set.seed(0)
> lik <- sample(c(0:3, NA), 150, replace=TRUE)
> lik <- factor(lik, levels=0:3, labels=c('no', 'maybe no', 'maybe yes', 'yes'))
> tn <- table(lik, useNA="always")
> tn
lik
       no  maybe no maybe yes       yes      <NA> 
       22        33        34        37        24 

I "nice" table could look like this

  no maybe no maybe yes  yes <NA>
n 24       34        37   29   26
% 36       51      55.5 43.5   39

Please pay attention here on the fact that 37 and 29 are displayed without digits!

If I would use rbind() here there are digits. See what I tried so far

> tp <- sapply(tn, function(x) { sum(tn) / 100 * x })
> rbind(tn, tp)
   no maybe no maybe yes  yes <NA>
tn 22     33.0        34 37.0   24
tp 33     49.5        51 55.5   36

A problem with this is, how to set the row names (e.g. tn -< n) and how to prevent to printing the numbers in the first row with digits.

I am fully open for suggestion about how likert data could be display nice and easy (in the meaning of: readable for non-R-users e.g. SPSS-users) in plain text.


Solution

  • If I understand your question correctly, I believe that you can use the kable function from the knitr package to solve your problem:

    tab <- rbind(tn, tp)
    rownames(tab) <- c("n", "%")
    knitr::kable(tab, digits=0)
    

    This results in the following output

    |   | no| maybe no| maybe yes| yes| NA|
    |:--|--:|--------:|---------:|---:|--:|
    |n  | 22|       33|        34|  37| 24|
    |%  | 33|       50|        51|  56| 36|
    

    EDIT: sorry I now see that you want to keep the decimals in the second row. Unfortunately kable sets digits column-wise, so this will not help you. What you could do instead is this:

    knitr::kable(t(tab))
    

    resulting in

    |          |  n|    %|
    |:---------|--:|----:|
    |no        | 22| 33.0|
    |maybe no  | 33| 49.5|
    |maybe yes | 34| 51.0|
    |yes       | 37| 55.5|
    |NA        | 24| 36.0|
    

    EDIT2: Your percentages do not seem to add up to 100%; I am not sure why that is, but the following would give percentages that add up to 100% in total:

    tab <- cbind(tn, tn / sum(tn) * 100)
    colnames(tab) <- c("n", "%")
    knitr::kable(tab, digits = c(0, 1))
    
    |          |  n|    %|
    |:---------|--:|----:|
    |no        | 22| 14.7|
    |maybe no  | 33| 22.0|
    |maybe yes | 34| 22.7|
    |yes       | 37| 24.7|
    |NA        | 24| 16.0|