该包foreign和haven可用于导入和导出文件从各种喜欢的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
要将数据帧导出到其他统计包,可以使用写入功能。这将写入2个文件,一个包含数据,一个包含指令,另一个包需要读取数据。write.foreign()
# 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")
SPSS存储的文件也可以通过read.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.missingsif 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.