【问题标题】:How to get labelled spss data back which is converted by as_factor in R如何获取由 R 中的 as_factor 转换的带标签的 spss 数据
【发布时间】:2020-09-12 19:28:44
【问题描述】:

我正在处理 R 中的 SPSS 数据。要修改/附加来自不同文件的数据,我必须将数据转换为因子(as_factor(x, levels = "both") 方法)。现在我需要将数据写回 .SAV 文件,但我无法将因子变量转换为标记数据。请看下面的代码 sn-p:-

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】:

    是的,使用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" ...
    

    【讨论】:

    • 这可能会导致信息丢失问题。尝试使用set.seed(620) 运行。使用该种子,此方法将标签“坏”关联到值 4 而不是 5,因为因子中没有 3 的水平。
    【解决方案2】:

    这有点混乱,但它适用于您提供的小示例(不确定它将如何用于您的真实数据)。第一个问题是as_factor 使用levels="both" 选项分配的因子水平非常混乱。您可以转换为数字,然后使用 haven 包中的 labelled(),但这可能会导致一些信息丢失。相反,我所做的是选择levels="default" 选项并使用labelled 包中的to_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() 函数中。

    【讨论】:

    • 谢谢!!这正是我所需要的。
    猜你喜欢
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2021-06-22
    • 2020-04-23
    • 2021-06-28
    • 2012-04-28
    相关资源
    最近更新 更多