简体   繁体   中英

What is the best way to import spss file in R with value labels?

I have a spss file which contents variables and value labels. I saw foreign package with read.spss function:

data <- read.spss("2017.sav", to.data.frame = TRUE, use.value.labels = TRUE)

If i use use.value.labels = TRUE , all string change to factor variables and i dont want it because they are not factor all.

I found one solution but i dont know if it is the best way to do it

1º First read spss file with previous sentence
2º select which variables are not factor and change it to string with:

cols <- c("x", "ab")

data[cols] <- lapply(data[cols], as.character)

if i dont use use.value.labels = TRUE i will have not value labels and i cannot export file correctly

I dont know why, but I can't install a "foreign" package.

Here is what I did instead to import a dataset from SPSS to R (through Excel):

  1. Open your data in SPSS.
  2. Export dataset from SPSS to Excel, but make sure to choose the "Save value labels where defined instead of data values" option at the very bottom.
  3. Open R.
  4. Import dataset from Excel.

Now, you have a dataset in R with value labels.

You can also use the memisc package:

sav <- spss.system.file("file.sav")
df <- as.data.set(sav)

My company regularly deals with SAV files and we extract out the metadata separately. With the foreign package, you can get the metadata out in a few different ways (after you have loaded the file in):

data.label.table <- attr(sav, "label.table")
missings <- attr(sav, "missings")

The other bits require various lapply and sapply functions to get them out. The script I have is quite long, so I will not share it here. If you read the data in with read.spss(sav, to.data.frame = TRUE) you can get:

VariableLabels <- unname(attr(sav, "variable.labels"))

Use the haven package:

library(haven)
data <- read_sav("2017.sav") 

The labels are shown in the RStudio viewer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM