使用来自UCI机器学习库(here)
的着名“成人”数据集数据集如下所示:
Observations: 32,561
Variables: 15
$ AGE <int> 39, 50, 38, 53, 28, 37, 49, 52, 31, 42, 37, 30, 23, 32, 40, 34, 25, 32, 38, 43, 40, 54, 35, 43, 59, ...
$ WORKCLASS <chr> "State-gov", "Self-emp-not-inc", "Private", "Private", "Private", "Private", "Private", "Self-emp-no...
$ FNLWGT <int> 77516, 83311, 215646, 234721, 338409, 284582, 160187, 209642, 45781, 159449, 280464, 141297, 122272,...
$ EDUCATION <chr> "Bachelors", "Bachelors", "HS-grad", "11th", "Bachelors", "Masters", "9th", "HS-grad", "Masters", "B...
$ EDUCATIONNUM <int> 13, 13, 9, 7, 13, 14, 5, 9, 14, 13, 10, 13, 13, 12, 11, 4, 9, 9, 7, 14, 16, 9, 5, 7, 9, 13, 9, 10, 9...
$ MARITALSTATUS <chr> "Never-married", "Married-civ-spouse", "Divorced", "Married-civ-spouse", "Married-civ-spouse", "Marr...
$ OCCUPATION <chr> "Adm-clerical", "Exec-managerial", "Handlers-cleaners", "Handlers-cleaners", "Prof-specialty", "Exec...
$ RELATIONSHIP <chr> "Not-in-family", "Husband", "Not-in-family", "Husband", "Wife", "Wife", "Not-in-family", "Husband", ...
$ RACE <chr> "White", "White", "White", "Black", "Black", "White", "Black", "White", "White", "White", "Black", "...
$ SEX <chr> "Male", "Male", "Male", "Male", "Female", "Female", "Female", "Male", "Female", "Male", "Male", "Mal...
$ CAPITALGAIN <int> 2174, 0, 0, 0, 0, 0, 0, 0, 14084, 5178, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...
$ CAPITALLOSS <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2042, 0, 0, 0, 0, 0, 0, 0, 0, 1...
$ HOURSPERWEEK <int> 40, 13, 40, 40, 40, 40, 16, 45, 50, 40, 80, 40, 30, 50, 40, 45, 35, 40, 50, 45, 60, 20, 40, 40, 40, ...
$ NATIVECOUNTRY <chr> "United-States", "United-States", "United-States", "United-States", "Cuba", "United-States", "Jamaic...
$ ABOVE50K <int> 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0...
我使用以下方法将类字符的所有变量更改为因子:
df <- df %>% mutate_if(is_character, as.factor)
现在我想看看每个因子变量的水平,我可以这样做:
levels(df2$working_class)
levels(df2$education)
levels(df2$marital_status)
等等每个因子变量。当然,使用purrr包应该有一种更简单的方法。类似的东西:
df %>% map_if(is.factor, levels)
不幸的是,即使是类整数的列,也会选择所有内容。
我应该如何使地图适用于仅考虑因子变量并返回其水平? 感谢
答案 0 :(得分:1)
希望这会有所帮助==
library(df)
df %>% select_if(is.factor) %>%
sapply(levels)