R 如果列的类型不常见,如何检查其类型?

R 如果列的类型不常见,如何检查其类型?,r,dplyr,r-haven,R,Dplyr,R Haven,我从一个.sav文件中获得了一些SPSS数据,并试图在R中使用它。许多变量都是haven_类型的。我想使用mutate_if()将它们转换为double。如何为mutate_if()创建一个谓词,该谓词将捕获类型为haven_的所有列?haven库中有一个is.label()函数。我们可以使用mutate\u if根据条件将函数应用于列。这里,在下面的可复制示例中,标记的属性位于“物种”列上,该列被转换为因子 library(dplyr) library(haven) iris1 <- i

我从一个.sav文件中获得了一些SPSS数据,并试图在R中使用它。许多变量都是haven_类型的。我想使用mutate_if()将它们转换为double。如何为mutate_if()创建一个谓词,该谓词将捕获类型为haven_的所有列?haven库中有一个is.label()函数。

我们可以使用
mutate\u if
根据条件将函数应用于列。这里,在下面的可复制示例中,
标记的
属性位于“物种”列上,该列被转换为
因子

library(dplyr)
library(haven)
iris1 <- iris %>%
            mutate_if(is.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 #...
数据
数据(iris)
鸢尾属
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"))