1

我已使用 rio 将 SAS 数据导入 R:

library(rio)
r<-import("S:/MyFolder/MyData.sas7bdat", catalog_file = "S:/MyFolder/formatsforr.sas7bcat")  

这给出了我的 r,它具有列 r$Race(存储原子值 1、2、3 和 4),它的属性似乎存储了我的 Race 格式(0="All", 1="White", . .., 8="未知", ...)。我想使用属性将 r$Race 转换为一个因子。我想为许多列执行此操作。

如果我使用了 Haven,我可以这样做:

library(haven)
h <- read_sas("S:/MyFolder/MyData.sas7bdat", "S:/MyFolder/formatsforr.sas7bcat")  
h$Race <- as_factor(h$Race)  # as_factor is a haven function that converts the column to a factor, using the format to label the factor values.

但是 as_factor 因 r 失败(使用 rio 创建的对象)。

我希望只使用 rio,出于其他原因,我们更喜欢使用 rio。我正在尝试为我的卫生部门的其他编码人员创建简单的示例。我想尽量减少他们需要学习和加载的包的数量,这样我们就可以集中学习。

如果这有帮助: as_factor(r$Race)返回:

UseMethod(“as_factor”)中的错误:没有适用于“as_factor”的方法应用于类“c('double','numeric')”的对象

str(r$Race)返回:

atomic [1:7776] 1 2 3 4 1 2 3 4 1 2 ... - attr( , "label")= chr "Race (1=W,2=B,3=NatAm/AKNat,4=Asian/ PacIs)" - attr( , "format.sas")= chr "POPEST199XRACE" - attr( , "labels")= Named num [1:10] 0 1 2 3 4 0 1 2 3 4 ..- attr( , "names")= chr [1:10] "Total" "White" "Black" "American Indian or Alaska Native" ...

str(h$Race)返回:

“标记”类原子 [1:7776] 1 2 3 4 1 2 3 4 1 2 ... ..- attr( , "label")= chr "Race (1=W,2=B,3=NatAm/ AKNat,4=Asian/PacIs)" ..-attr( , "format.sas")= chr "POPEST199XRACE" ..- attr( , "labels")= Named num [1:10] 0 1 2 3 4 0 1 2 3 4 .. ..- attr( , "names")= chr [1:10] "Total" "White" "Black" "American Indian or Alaska Native" ...

在运行 import(...) 之后,运行:

    dput(head(r$Race))# returns this: 
c(1, 2, 3, 4, 1, 2)

在运行 read_sas(...) 之后,运行:

     dput(head(h$Race)) # returns this:
     structure( c(1, 2, 3, 4, 1, 2), 
       labels = structure(c(0, 1, 2, 3, 4, 0, 1, 2, 3, 4),
       .Names = c("Total", "White", "Black", "American Indian or Alaska Native", 
                "Asian or Pacific Islander", "Total", "White", "Black", 
                "American Indian or Alaska Native", "Asian or Pacific Islander")),
                   class = "labelled")

我没有找到在线 .sas7bcat 文件。我可以发布 SAS 代码来创建它和数据文件。

4

1 回答 1

0

我放弃了尝试使用rio,而是使用了have。使用import()调用时catalog_file =,rio 可以在创建的 R 对象的属性中捕获 SAS 格式信息,但我不知道如何使用它们。查看 Haven 的 as_factor 函数,我看到有些复杂的逻辑 Have 用来利用类似的属性(通过 Haven 的函数创建read_sas())。看到它的复杂性,我并没有试图模仿它来应用到rio导入对象的属性。

于 2018-04-06T21:12:55.433 回答