programing

R로 SPSS 파일 읽기

kingscode 2021. 1. 14. 22:55
반응형

R로 SPSS 파일 읽기


R을 배우려고하고 SPSS에서 열 수있는 SPSS 파일을 가져오고 싶습니다.

read.spssfrom foreignspss.getfrom을 사용해 보았습니다 Hmisc. 두 오류 메시지는 동일합니다.

내 코드는 다음과 같습니다.

## install.packages("Hmisc")
library(foreign)

## change the working directory
getwd()
setwd('C:/Documents and Settings/BTIBERT/Desktop/')

## load in the file
## ?read.spss
asq <- read.spss('ASQ2010.sav', to.data.frame=T)

그리고 결과 오류 :

read.spss ( "ASQ2010.sav", to.data.frame = T) 오류 : 시스템 파일 헤더 읽기 오류 추가 : 경고 메시지 : In read.spss ( "ASQ2010.sav", to.data.frame = T) : ASQ2010.sav : 위치 0 : 문자`\ 000 '(

또한 SPSS 파일을 SPSS 7 .sav 파일로 저장해 보았습니다 (이전에는 SPSS 18을 사용했습니다).

경고 메시지 : 1 : In read.spss ( "ASQ2010_test.sav", to.data.frame = T) : ASQ2010_test.sav : Unrecognized record type 7, subtype 14 found in system file 2 : In read.spss ( "ASQ2010_test. sav ", to.data.frame = T) : ASQ2010_test.sav : 인식 할 수없는 레코드 유형 7, 시스템 파일에서 하위 유형 18 발견


나는 비슷한 문제가 있었고 read.spss도움 의 힌트를 따라 해결했습니다 . memisc대신 패키지 사용하여 다음과 같은 휴대용 SPSS 파일을 가져올 수 있습니다 .

data <- as.data.set(spss.portable.file("filename.por"))

마찬가지로 .sav 파일의 경우 :

data <- as.data.set(spss.system.file('filename.sav'))

이 경우 일부 문자열 값을 놓친 것처럼 보이지만 휴대용 가져 오기는 원활하게 작동합니다. spss.portable.file클레임 도움말 페이지 :

임포터 메커니즘은 대부분의 파일 헤더 구문 분석이 R에서 수행되므로 패키지 "foreign"의 read.spss 및 read.dta보다 더 유연하고 확장 가능합니다. 또한 대규모 데이터 세트를 효율적으로로드하도록 조정됩니다. 가장 중요한 것은 importer 객체가이 패키지에서 제공하는 레이블, missing.values ​​및 설명을 지원한다는 것입니다.


read.spss내가 사용하는 패키지라는, 그래서 조금 오래된 것 같다 memisc.

이 작업을 수행하려면 다음을 수행하십시오.

install.packages("memisc")
data <- as.data.set(spss.system.file('yourfile.sav'))

이 게시물이 오래되었다는 것을 알고 있지만 Qualtrics SPSS 파일을 R에로드하는 데 문제가있었습니다. R의 read.spss 코드는 오래 전에 PSPP에서 왔으며 한동안 업데이트되지 않았습니다. (그리고 Hmisc의 코드는 read.spss ()도 사용하므로 운이 없습니다.)

좋은 소식은 Qualtrics의 "데이터 다운로드"페이지에서 "Short-255 (SPSS 12.0 이하)"의 "문자열 너비"를 지정하는 한 PSPP 0.6.1이 파일을 잘 읽어야한다는 것입니다. PSPP로 읽고 새 사본을 저장하면 업무에 참여할 수 있습니다. 어색하지만 무료입니다.

대체 텍스트,


다음을 시도해 볼 수도 있습니다.

setwd("C:/Users/rest of your path")

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

한 폴더에서 모든 파일을 읽으려면 :

temp <- list.files(pattern = "*.sav")
read.all <- sapply(temp, read_sav)

R read.spss 구현이 불완전하거나 손상된 것 같습니다. 그러나 R2.10.1은 R2.8.1보다 낫습니다. R은 2.10.1 (내가 가지고있는 최신 버전)에서도 sav 파일의 사용자 지정 속성에 대해 화를내는 것 같습니다. R은 또한 파일의 문자 인코딩 필드를 이해하지 못할 수 있으며 특히 SPSS 유니 코드 파일에서 작동하지 않을 수 있습니다.

SPSS에서 파일을 열고 사용자 정의 속성을 삭제 한 다음 파일을 다시 저장해보십시오. SPSS 명령으로 사용자 정의 속성이 있는지 확인할 수 있습니다.

표시 속성.

그렇다면 삭제하고 (VARIABLE ATTRIBUTE 및 DATAFILE ATTRIBUTE 명령 참조) 다시 시도하십시오.

HTH, 존 펙


위의 솔루션 또는 현재 사용중인 솔루션 SPSSR사용하여 파일을 읽을 수 있습니다 . 명령이 제대로 읽을 수 있도록 파일과 함께 제공되는지 확인하십시오. 나는 같은 오류가 있었고 문제는 SPSS가 해당 파일에 액세스 할 수 없다는 것입니다. 파일 경로가 올 바르고 파일에 액세스 할 수 있으며 올바른 형식인지 확인해야합니다.

library(foreign)
asq <- read.spss('ASQ2010.sav', to.data.frame=TRUE)

As far as warning message is concerned, It does not affect the data. The record type 7 is used to store features in newer SPSS software to make older SPSS software able to read new data. But does not affect data. I have used this numerous times and data is not lost.

You can also read about this at http://r.789695.n4.nabble.com/read-spss-warning-message-Unrecognized-record-type-7-subtype-18-encountered-in-system-file-td3000775.html#a3007945


If you have access to SPSS, save file as .csv, hence import it with read.csv or read.table. I can't recall any problem with .sav file importing. So far it was working like a charm both with read.spss and spss.get. I reckon that spss.get will not give different results, since it depends on foreign::read.spss

Can you provide some info on SPSS/R/Hmisc/foreign version?


Another solution not mentioned here is to read SPSS data in R via ODBC. You need:

  1. IBM SPSS Statistics Data File Driver. Standalone driver is enough.
  2. Import SPSS data using RODBC package in R.

See the example here. However I have to admit that, there could be problems with very big data files.


For me it works well using memisc!

install.packages("memisc")
load('memisc')
Daten.Februar <-as.data.set(spss.system.file("NPS_Februar_15_Daten.sav"))
names(Daten.Februar)

There is no such problem with packages you are using. The only requirement for read a spss file is to put the file into a PORTABLE format file. I mean, spss file have *.sav extension. You need to transform your spss file in a portable document that uses *.por extension.

There is more info in http://www.statmethods.net/input/importingdata.html


In my case this warning was combined with a appearance of a new variable before first column of my data with values -100, 2, 2, 2, ..., a shift in the correspondence between labels and values and the deletion of the last variable. A solution that worked was (using SPSS) to create a new dump variable in the last column of the file, fill it with random values and execute the following code: (filename is the path to the sav file and in my case the original SPSS file had 62 columns, thus 63 with the additional dumb variable)

library(memisc)
data <- as.data.set(spss.system.file(filename))

copyofdata = data
for(i in 2:63){
  names(data)[i] <- names(copyofdata)[i-1]
}
data[[1]] <- NULL

newcopyofdata = data
for(i in 2:62){
  labels(data[[i]]) <- labels(newcopyofdata[[i-1]])
}
labels(data[[1]]) <- NULL

Hope the above code will help someone else.


I agree with @SDahm that the haven package would be the way to go. I myself have struggled a bit with string values when starting to use it, so I thought I'd share my approach on that here, too.

The "semantics" vignette has some useful information on this topic.

library(tidyverse)
library(haven)

# Some interesting information in here
vignette('semantics')

# Get data from spss file
df <- read_sav(path_to_file)

# get value labels
df <- map_df(.x = df, .f = function(x) {
  if (class(x) == 'labelled') as_factor(x)
  else x})
# get column names
colnames(df) <- map(.x = spss_file, .f = function(x) {attr(x, 'label')})

1)

I've found the program, stat-transfer, useful for importing spss and stata files into R.

It resolves the issue you mention by converting spss to R dataset. Also very useful for subsetting super large datasets into smaller portions consumable by R. Not free, but a very useful tool for working with datasets from different programs -- especially if you don't have access to them.

2)

Memisc package also has an spss function worth trying.


Turn your UNICODE in SPSS off

Open SPSS without any data open and run the code below in your syntax editor

SET UNICODE OFF.

Open the data set and resave it to remove the Unicode

read.spss('yourdata.sav', to.data.frame=T) works correctly then

ReferenceURL : https://stackoverflow.com/questions/3136293/read-spss-file-into-r

반응형