这有点混乱,但它适用于您提供的小示例(不确定它将如何用于您的真实数据)。第一个问题是as_factor
使用该levels="both"
选项分配的因子水平非常混乱。您可以转换为数字,然后labelled()
从haven
包中使用,但这可能会导致一些信息丢失。相反,我所做的是选择levels="default"
选项并使用包中的to_labelled()
功能labelled
。在这个函数中,我为所有因子级别(不仅仅是您开始使用的两个标签)分配了标签,否则这些将被转换为NA
.
代码:
library(haven)
library(labelled)
set.seed(617)
(x = labelled(sample(5, 10, replace = TRUE), c(Bad = 1, Good = 5)))
(x1 = as_factor(x, levels="default"))
(x2 = to_labelled(x1, labels=c(Bad = 1, '2'=2, '3'=3, '4'=4, Good = 5)))
输出:
> set.seed(617)
> (x = labelled(sample(5, 10, replace = TRUE), c(Bad = 1, Good = 5)))
<Labelled integer>
[1] 1 4 1 1 1 1 3 3 3 4
Labels:
value label
1 Bad
5 Good
> (x1 = as_factor(x, levels="default"))
[1] Bad 4 Bad Bad Bad Bad 3 3 3 4
Levels: Bad 3 4 Good
> (x2 = to_labelled(x1, labels=c(Bad = 1, '2'=2, '3'=3, '4'=4, Good = 5)))
<Labelled double>
[1] 1 4 1 1 1 1 3 3 3 4
Labels:
value label
1 Bad
2 2
3 3
4 4
5 Good
这使您从一个因素回到标记数据。如果您必须将levels="both"
选项与 一起使用as_factor()
,您可以这样做,但您需要确保将因子水平to_labelled()
适当地复制回函数中。