Label book for R

Sometimes, when you explore a new dataset, variable names don’t make much sense. In SPSS you would just look at the labels, in R it’s not that straightforward: checking codebooks all the time is tedious, reading a questionnaire and trying to guess which variable corresponds to each question is even less reliable. If your data has labels as attributes, or you have read .sav datafile into R with haven or foreign package, it would be handy to have a searchable table of all the variable and value labels in the dataset. I looked it up and didn’t find such a function, so I have written a little simple function myself.
 
UPD. Now this function is a part of my R package LittleHelpers.

The function gets the attributes of variables and value labels and put them in a nicely formatted table.

Use:
label_book(df, max.val=25, vars="all", view=TRUE)
There are three arguments:

  • df – data.frame, result of reading spss file by packages ‘haven’ or ‘foreign’
  • max.vals – integer, how many value labels per each variable shoud be listed in the table, default is 25
  • vars – can be integer, character, or range of integers or characters. Variables indexes or names for getting subsets of label book.
  • view – logical, whether the result should be shown in the RStudio viewer pane. Defualt is TRUE. If FALSE, html file named ‘label_book_output.html’ is saved in your working directory.

The only extra package required is knitr.

Example

# Read the data
 ess8<- haven::read_sav("ESS8e01.sav")
# Download the function
 eval(parse(text=getURL("https://raw.githubusercontent.com/MaksimRudnev/LittleHelpers/master/label_book/label_book.R")))
# Use the function
 label_book(ess8, max.vals=11, vars=45:50)

Result

Label Book for “ess8”

Variables Variable labels Values Value labels
contplt Contacted politician or government official last 12 months 1 Yes
2 No
7 Refusal
8 Don’t know
9 No answer
wrkprty Worked in political party or action group last 12 months 1 Yes
2 No
7 Refusal
8 Don’t know
9 No answer
wrkorg Worked in another organisation or association last 12 months 1 Yes
2 No
7 Refusal
8 Don’t know
9 No answer
badge Worn or displayed campaign badge/sticker last 12 months 1 Yes
2 No
7 Refusal
8 Don’t know
9 No answer
sgnptit Signed petition last 12 months 1 Yes
2 No
7 Refusal
8 Don’t know
9 No answer
pbldmn Taken part in lawful public demonstration last 12 months 1 Yes
2 No
7 Refusal
8 Don’t know
9 No answer

Leave a Reply

Your email address will not be published. Required fields are marked *