我有一些来自 .sav 文件的 SPSS 数据,并正在尝试在 R 中使用它。许多变量的类型为 Have_labelled。我想使用 mutate_if() 将它们转换为双精度。如何为 mutate_if() 创建一个谓词,以捕获所有类型为 Have_labelled 的列?Have 库中有一个 is.labelled() 函数。
问问题
126 次
1 回答
3
我们可以使用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"))
于 2019-07-20T15:21:17.893 回答