Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将R中的as_因子转换成带标签的spss数据_R_Spss_R Haven - Fatal编程技术网

如何将R中的as_因子转换成带标签的spss数据

如何将R中的as_因子转换成带标签的spss数据,r,spss,r-haven,R,Spss,R Haven,我正在R中处理SPSS数据。要修改/附加来自不同文件的数据,我必须将数据转换为因子作为_factorx,levels=两种方法。现在我需要将数据写回.SAV文件,但我无法将因子变量转换为带标签的数据。请参阅下面的代码片段:- x <- labelled(sample(5, 10, replace = TRUE), c(Bad = 1, Good = 5)) x1<-as_factor(x, levels = "both") x2<-labelled(x1) Error: `x

我正在R中处理SPSS数据。要修改/附加来自不同文件的数据,我必须将数据转换为因子作为_factorx,levels=两种方法。现在我需要将数据写回.SAV文件,但我无法将因子变量转换为带标签的数据。请参阅下面的代码片段:-

x <- labelled(sample(5, 10, replace = TRUE), c(Bad = 1, Good = 5))
x1<-as_factor(x, levels = "both")
x2<-labelled(x1)

Error: `x` must be a numeric or a character vector
是否有方法将因子转换为spss数据。

是,使用to_labelledx1:


这有点混乱,但它适用于您给出的小示例,不确定它将如何应用于您的真实数据。第一个问题是,由as_factor分配的因子级别与levels=两个选项相当混乱。您可以将其转换为数字,然后使用haven软件包中的标签,但这可能会导致某些信息丢失。相反,我所做的是选择levels=default选项,并使用标签包中的to_标签函数。在这个函数中,我为所有因子级别分配了标签,而不仅仅是您开始使用的两个标签,否则这些标签将转换为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_标签的函数中。

这可能会导致信息丢失问题。试着用set.seed620跑步。使用该种子,此方法将坏标签与值4(而不是5)关联,因为因子中没有级别3。谢谢!!这正是我所需要的。
> 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