如何获得带标签的spss数据,该数据由R中的as_factor转换

问题描述 投票:0回答:1

我正在R中处理SPSS数据。要修改/追加来自不同文件的数据,我必须将数据转换为factor(as_factor(x,level =“ both”)方法)。现在,我需要将数据写回到.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数据。

r spss r-haven
1个回答
0
投票

是,使用to_labelled(x1)

library(tidyverse)
library(labelled)

> x <- labelled(sample(5, 10, replace = TRUE), c(Bad = 1, Good = 5))
> str(x)
'haven_labelled' int [1:10] 2 4 3 1 5 5 2 5 5 5
- attr(*, "labels")= Named num [1:2] 1 5
 ..- attr(*, "names")= chr [1:2] "Bad" "Good"

> x1 <- to_factor(x, levels = "labels")
> str(x1)
Factor w/ 5 levels "Bad","2","3",..: 2 4 3 1 5 5 2 5 5 5

> x2 <- to_labelled(x1)
> str(x2)
'haven_labelled' num [1:10] 2 4 3 1 5 5 2 5 5 5
- attr(*, "labels")= Named int [1:5] 1 2 3 4 5
 ..- attr(*, "names")= chr [1:5] "Bad" "2" "3" "4" ...

0
投票

这有点混乱,但是它适用于您提供的小示例(不确定如何将其用于您的真实数据)。第一个问题是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()函数中。

© www.soinside.com 2019 - 2024. All rights reserved.