我已使用 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 代码来创建它和数据文件。