如何将要在 SAS、SPSS 或 STATA 中使用的数据导入 R?

How can I import data into R that is meant for use in SAS, SPSS, or STATA?

我正在尝试从 R 中的全国健康访谈调查中读取数据:http://www.cdc.gov/nchs/nhis/nhis_2011_data_release.htm。数据是样本成人。 SAScii 库实际上有一个函数 read.SAScii,其文档中有一个我想使用的相同数据集的示例。问题是 "doesn't work":

NHIS.11.samadult.SAS.read.in.instructions <- 
  "ftp://ftp.cdc.gov/pub/Health_Statistics/NCHS/Program_Code/NHIS/2011/SAMADULT.sas"
NHIS.11.samadult.file.location <- 
  "ftp://ftp.cdc.gov/pub/Health_Statistics/NCHS/Datasets/NHIS/2011/samadult.zip"

#store the NHIS file as an R data frame!
NHIS.11.samadult.df <- 
  read.SAScii ( 
    NHIS.11.samadult.file.location , 
    NHIS.11.samadult.SAS.read.in.instructions , 
    zipped = T, )

#or store the NHIS SAS import instructions for use in a 
#read.fwf function call outside of the read.SAScii function
NHIS.11.samadult.sas <- parse.SAScii( NHIS.11.samadult.SAS.read.in.instructions )

#save the data frame now for instantaneous loading later
save( NHIS.11.samadult.df , file = "NHIS.11.samadult.data.rda" )

但是,当 运行 时,我得到错误 Error in toupper(SASinput) : invalid multibyte string 533

Stack Overflow 上的其他人也有类似的错误,但对于 read.delimread.csv 等函数,建议尝试将参数更改为 fileEncoding="latin1"read.SAScii 的问题是它没有这样的参数 fileEncoding

参见: R: invalid multibyte string and Invalid multibyte string in read.csv

以防万一有人遇到类似问题,我的问题和解决方案是 运行 options( encoding = "windows-1252" ) 就在 运行 为 read.SAScii 设置上述代码之前 read.SAScii 因为ASCII 文件适用于 SAS,因此适用于 Windows。我正在使用 Linux。

SAScii 库的作者实际上有另一个 Github 存储库 asdfree,他在其中具有用于下载所有可用年份的 CDC-NHIS 数据集的工作代码以及来自各种调查的许多其他数据集,例如美国住房调查、FDA 药物调查等。

以下link作者对本题问题的解答。从那里,您可以轻松找到 asdfree 存储库的 link:https://github.com/ajdamico/SAScii/issues/3

就此数据集而言,https://github.com/ajdamico/asdfree/blob/master/National%20Health%20Interview%20Survey/download%20all%20microdata.R#L8-L13 中的代码可以解决问题,但它没有正确地将列编码为因子或数字。好消息是,对于 NHIS 年中的任何给定数据集,只有不到 10 到 20 个数字列,其中将这些列一个一个地编码为数字并不那么痛苦,而将其余列编码为数字只需要一个遍历 non-numeric 列。

对我来说最简单的解决方案是 运行 SAS 程序,因为我只需要 2011 年的 Sample Adult 数据集,而且我能够使用安装了 SAS 的机器包含在 http://www.cdc.gov/nchs/nhis/nhis_2011_data_release.htm 以根据需要对列进行编码。最后,我使用 proc export 将 sas 数据集导出到一个 CSV 文件,然后我在 R 中轻松打开该文件,除了处理缺失值外,没有对数据进行任何必要的编辑。

如果您想使用成人样本以外的 NHIS 数据集,值得注意的是,当我 运行 2010 "Sample Adult Cancer" (http://www.cdc.gov/nchs/nhis/nhis_2010_data_release.htm) 可用的 SAS 程序并导出时将数据转换为 CSV,当我尝试在 R 中读取 CSV 文件时,存在列名少于实际列的问题。跳过第一行可以解决此问题,但您会丢失描述性列名。但是,您可以轻松导入相同的数据,而无需使用 asdfree 存储库中的 R 代码进行编码。请阅读那里的文档以获取更多信息。