讀寫 Stata SPSS 和 SAS 檔案

foreignhaven 可用於從各種其他統計軟體包(如 Stata,SPSS 和 SAS 以及相關軟體)匯入和匯出檔案。每個支援的資料型別都有一個 read 函式來匯入檔案。

# loading the packages
library(foreign)
library(haven)
library(readstata13)
library(Hmisc)

最常見資料型別的一些示例:

# reading Stata files with `foreign`
read.dta("path\to\your\data")
# reading Stata files with `haven`
read_dta("path\to\your\data")

foreign 包可以讀取 stata(.dta) 檔案中的 Stata 7-12 版本。根據開發頁面,read.dta 或多或少地被凍結,並且在 13+版本中不會更新。對於更新版本的 Stata,你可以使用 readstata13 軟體包或 haven。對於 readstata13,檔案是

# reading recent Stata (13+) files with `readstata13`
read.dta13("path\to\your\data")

用於讀取 SPSS 和 SAS 檔案

# reading SPSS files with `foreign`
read.spss("path\to\your\data.sav", to.data.frame = TRUE)
# reading SPSS files with `haven`
read_spss("path\to\your\data.sav")
read_sav("path\to\your\data.sav")
read_por("path\to\your\data.por")

# reading SAS files with `foreign`
read.ssd("path\to\your\data")
# reading SAS files with `haven`
read_sas("path\to\your\data")
# reading native SAS files with `Hmisc`
sas.get("path\to\your\data")   #requires access to saslib 
# Reading SA XPORT format ( *.XPT ) files
sasxport.get("path\to\your\data.xpt")  # does not require access to SAS executable

SAScii 包提供了接受 SAS SET 匯入程式碼並構造可以使用 read.fwf 處理的文字檔案的功能。事實證明,它對於匯入大型公共釋出資料集非常可靠。支援位於 https://github.com/ajdamico/SAScii

要將資料幀匯出到其他統計包,可以使用寫入函式 write.foreign()。這將寫入 2 個檔案,一個包含資料,另一個包含另一個包讀取資料所需的指令。

# writing to Stata, SPSS or SAS files with `foreign`
write.foreign(dataframe, datafile, codefile,
              package = c("SPSS", "Stata", "SAS"), ...)
write.foreign(dataframe, "path\to\data\file", "path\to\instruction\file", package = "Stata")

# writing to Stata files with `foreign`
write.dta(dataframe, "file", version = 7L,
          convert.dates = TRUE, tz = "GMT",
          convert.factors = c("labels", "string", "numeric", "codes"))

# writing to Stata files with `haven`
write_dta(dataframe, "path\to\your\data")

# writing to Stata files with `readstata13`
save.dta13(dataframe, file, data.label = NULL, time.stamp = TRUE,
  convert.factors = TRUE, convert.dates = TRUE, tz = "GMT",
  add.rownames = FALSE, compress = FALSE, version = 117,
  convert.underscore = FALSE)

# writing to SPSS files with `haven`
write_sav(dataframe, "path\to\your\data")

也可以通過這種方式使用 read.spss 讀取 SPSS 儲存的檔案:

 foreign::read.spss('data.sav', to.data.frame=TRUE, use.value.labels=FALSE, 
                     use.missings=TRUE, reencode='UTF-8')
# to.data.frame if TRUE: return a data frame
# use.value.labels if TRUE: convert variables with value labels into R factors with those levels
# use.missings if TRUE: information on user-defined missing values will used to set the corresponding values to NA.
# reencode character strings will be re-encoded to the current locale. The default, NA, means to do so in a UTF-8 locale, only.