我使用R来分析来自IPUMS的大型数据文件,这些文件在人口普查记录上发布了复杂的微观数据 . IPUMS将其摘录提供为SPSS,SAS或STATA文件 . 为了将数据导入R,我最幸运的是下载SPSS版本并使用"foreign"库中的 read.spss
函数:
library(foreign);
ipums <- read.spss("usa_00106.sav", to.data.frame = TRUE);
这项工作非常出色,除了这个永久的警告:
Warning message:
In `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels, :
duplicated levels in factors are deprecated
(如果有人感觉很英勇,我上传了压缩的.sav文件here(39Mb)以及.SPS file和更人性化的codebook . 这只是一个示例IPUM提取,并且像所有IPUM数据一样,不包含私人信息 . )
My question is whether my data is compromised by duplicate factors in the SPSS file or whether this is something I can fix after the import.
为了弄清楚哪个列是罪魁祸首,我写了一点诊断:
ipums <- read.spss("usa_00106.sav", to.data.frame = TRUE);
for (name in names(ipums)) {
type <- class(ipums[[name]]);
if (type == "factor") {
print(name);
print(anyDuplicated(levels(ipums[[name]])));
}
}
此循环正确地将列 BLPD
标识为罪魁祸首 . 那个's a detailed version of a person'的出生地在.SPS文件中有536个可能的值,由此代码确认:
fac <- levels(ipums$BPLD)
length(fac) #536
anyDuplicated(fac) #153
fac[153] #"Br. Virgin Islands, ns"
当我查看.SPS文件时,我确实看到该位置有两个条目:
26052 "Br. Virgin Islands, ns"
26069 "Br. Virgin Islands, ns"
但是,我没有在数据中看到此位置的单个实例:
NROW(subset(ipums, ipums$BPLD=="Br. Virgin Islands, ns")) #0
这很可能是因为这不是可能出现在数据中的常见位置,但我不能假设在未来的项目中总会出现这种情况 . So part two of my question is whether an SPSS file with duplicate factors will at least important the correct values, or whether a file that produces this warning message is potentially damaged.
至于修复问题,我看到一些相关的StackOverflow帖子,比如this one,但我不确定它们是否解决了我对来自第三方的复杂公共数据的问题 . 使用重复值清除因子的最有效方法是什么,这样我才能对数据充满信心?
2 回答
您可以尝试导入并将因子指定为false:
或者来自read.spss的帮助命令
SPSS不要求值标签的唯一性 . 在此数据集中,BLPD是一个字符串 . 我相信read.spss会创建一个具有重复级别的因子,但会将所有重复值分配给其中一个 . 您可以在读取数据后使用droplevels()来清除未使用的级别 .