【问题标题】:How can I check the type of a column if it is an unusual type?如果列是不寻常的类型,我如何检查它的类型?
【发布时间】:2019-07-20 14:57:24
【问题描述】:

我有一些来自 .sav 文件的 SPSS 数据,并正在尝试在 R 中使用它。许多变量的类型为 Have_labelled。我想使用 mutate_if() 将它们转换为双精度。如何为 mutate_if() 创建一个谓词来捕获所有类型为 Have_labelled 的列? Have 库中有一个 is.labelled() 函数。

【问题讨论】:

    标签: r dplyr r-haven


    【解决方案1】:

    我们可以使用mutate_if 根据条件将函数应用于列。在这里,在下面的可重现示例中,labelled 属性位于“物种”列上,该列被转换为 factor

    library(dplyr)
    library(haven)
    iris1 <- iris %>%
                mutate_if(is.labelled, factor) 
    

    或者另一种选择是使用class 创建逻辑条件

    iris1 <- iris %>%
               mutate_if(~ class(.) ==  "haven_labelled", factor)
    

    -检查结构

    str(iris)
    #'data.frame':  150 obs. of  5 variables:
    # $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
    # $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
    # $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
    # $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
    # $ Species     : 'haven_labelled' chr  "setosa" "setosa" "setosa" "setosa" ...
    #  ..- attr(*, "labels")= Named chr  "S" "ve" "vi"
    #  .. ..- attr(*, "names")= chr  "setosa" "versicolor" "virginica"
    
    str(iris1)
    #'data.frame':  150 obs. of  5 variables:
    # $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
    # $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
    # $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
    # $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
    # $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 #...
    

    数据

    data(iris)
    iris$Species <- labelled(as.character(iris$Species),
           c("setosa" = "S", "versicolor" = "ve", "virginica" = "vi"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-14
      • 2020-10-29
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      • 2011-02-27
      • 1970-01-01
      相关资源
      最近更新 更多