Soren V. Raben
Soren V. Raben

Reputation: 352

How to keep variable labels after raking in R Studio?

I think my problem is pretty simple to solve but as I'm totally new in R I don't know how to manage it.

So, I had to weight data from SPSS .sav dataset. First, I imported it into RStudio using foreign. Then I created another dataframe by iterake. However, after raking all variable labels are gone. I tried to copy labels from the source dataframe to weighted dataframe but - what is surprising - it seems R does not recognize source variable labels even though I see them in the RStudio window (below variable names). I mean after I load library labelled and launch var_label(SourceDF) I get only NULL values...

My goal is to copy new weighting variable into the source dataframe (and export the source back to the SPSS format) or copy variable labels from the source dataframe to the raked dataframe.

So:

  1. How to create a weighted dataframe with variable labels (through iterake)?

OR

  1. How to copy source variable labels to the weighted one?

This is the simplified code I created:

library(foreign)
library(iterake)
library(expss)
library(haven)

#source dataframe
df = read.spss("sourcedataset.sav", use.value.labels=TRUE, to.data.frame=TRUE)

#raking universe
uni = universe(data = df, category(name = "q1", 
                                   buckets = c("a", "b", "c", "d"), 
                                   targets = c(0.2,0.5,0.2,0.1), sum.1 = TRUE), 
                          category(name = "q2",
                                   buckets = c("e", "f"), 
                                   targets = c(0.8,0.2),
                                              sum.1 = TRUE), N = 1000)
#creation of the raked dataframe
df.wgt = iterake(universe = uni)```

Upvotes: 1

Views: 576

Answers (1)

Fnguyen
Fnguyen

Reputation: 1177

I you read through this thorough Documentation of variable labels you will find the necessary insight.

In short do the following:

  1. Save the imported value and variable labels after the import
  2. Reapply the saved labels after operations

The necessary commands are:

var_lab() #reads and sets variable labels

val_lab() #reads and sets value labels

variable_label <- var_lab(some_variable) #saving after import

#do stuff

var_lab(some_variable) <- variable_label #reapply labels

Upvotes: 1

Related Questions