2016-11-06 40 views
1

我使用haven包中的read_sav函数导入SPSS文件。因此,我有专栏名称和关联标签(labelled)。R - 从haven包使用read_sav后订购数据帧时丢失标签

我订购数据框时丢失了标签。我可以在订单前避免因素转换的问题,但这是一个错误还是一个正常的行为?

这是一个简单的例子。

DataForExample <- structure(list(CollectorNm = structure(c("Email Invitation 8", "Email Invitation 8", "Email Invitation 8", "Email Invitation 8", "Email Invitation 8", "Email Invitation 8"), label = "CollectorNm"), q0001 = structure(c(1, 1, 1, 1, 1, 1), label = "Avez-vous déjà suivi la formation Atlas-Vente des 18 et 19 octobre ?", class = "labelled", labels = structure(c(1, 2), .Names = c("Oui, j'ai bien suivi cette formation.", "Non, je n'y ai pas participé." ))), q0002_0001 = structure(c(3, 3, 3, 2, 3, 3), label = "La formation dans son ensemble", class = "labelled", labels = structure(c(1, 2, 3, 4), .Names = c("pas du tout satisfait", "plutôt pas satisfait", "plutôt satisfait", "très satisfait")))), .Names = c("CollectorNm", "q0001", "q0002_0001"), class = c("tbl_df", "tbl", "data.frame" ), row.names = c(NA, -6L))

View(DataForExample) # OK Toto <- DataForExample[order(DataForExample$q0001_0001),] View(Toto) # NOK : the labels disappeared

感谢

回答

1

您需要与支持加载包子集化操作为labelled类。最好在haven之后加载它。至少有两个包含此类支持的软件包:Hmiscexpss。免责声明:我是expss软件包的作者。

UPDATE。修复标记的类。

haven似乎没有为所有带标签的变量设置labelled类。所以我们需要修复它:

library(expss) 

for(each in colnames(DataForExample)){ 
    if(!("labelled" %in% class(DataForExample[[each]])) && 
     (!is.null(var_lab(DataForExample[[each]])) || 
     !is.null(val_lab(DataForExample[[each]])) 
     )) { 
     class(DataForExample[[each]]) = union("labelled", class(DataForExample[[each]])) 
    } 
} 

View(DataForExample) # OK 
Toto <- DataForExample[order(DataForExample$q0001),] 
View(Toto) # OK 
+0

谢谢。对于我所做的例子来说没问题,但问题仍然存在于更复杂的数据框架中。我确切地说我尝试了这两个软件包。当(未来)因素变量和(未来)字符串变量存在时,问题似乎就出现了,所以我改变了我的问题中的例子。 – Kumpelka

+0

@Kumpelka查看更新。 –