2

I read a SPSS dataset using R. If I view the dataset, there is text description under the variable names. They should be understood as labels of the variables. But I cannot extract them by using label function. Is there anyway to extract them and define them as the label of the variables?enter image description here


Turns out these texts are stored as the attributes of the dataset. I can extract them using attr function

var.labels <- attr(data, "variable.labels")

Then by the smart answer from R: Assign variable labels of data frame columns, I can assign them as variable labels by

label(data) = as.list(var.labels[match(names(data), names(var.labels))])
Yuge Hao
  • 21
  • 1
  • 3
  • 2
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. How are you importing this data? What exactly does the `label` function return? The labels are probably stored on the object in the attributes somewhere. Seeing a `dput()` should make it clear where. – MrFlick Mar 20 '19 at 17:18

2 Answers2

6

I am assuming you are importing data from a source like SPSS that allows column description for labels right?

R does not show the label description unfortunately as specified in here: https://www.r-bloggers.com/getting-variable-labels-in-r-from-spss/

However as the gentleman said in this previous post How to access R data.frame column descriptions after read.spss, you can access the description (which in R are called attributes) using the following code:

attributes(data)

attributes(data)$AID
0

do u read the database with foreign? or do you read it with haven?

if you read it with foreign, the labelled variable are read as factors, so you can search how. if you read it with haven::read_spss, thou shall read them with labelled::val_labels (all of them) or with labelled::val_label (an specific value)