r - R 配方中的一种热编码仅因子变量
问题描述
我有一个df
像这样的数据框
height age dept
69 18 A
44 8 B
72 19 B
58 34 C
我想只对因子变量进行一次热编码(只有 dept 是一个因子)。我怎样才能做到这一点?
目前我正在选择一切..
并收到此警告:
警告消息:以下变量不是因子向量,将被忽略:height
,age
ohe <- df %>%
recipes::recipe(~ .) %>%
recipes::step_dummy(tidyselect::everything()) %>%
recipes::prep() %>%
recipes::bake(df)
解决方案
使用where
withis.factor
代替everything
library(dplyr)
df %>%
recipes::recipe(~ .) %>%
recipes::step_dummy(tidyselect:::where(is.factor)) %>%
recipes::prep() %>%
recipes::bake(df)
-输出
# A tibble: 4 × 4
height age dept_B dept_C
<int> <int> <dbl> <dbl>
1 69 18 0 0
2 44 8 1 0
3 72 19 1 0
4 58 34 0 1
数据
df <- structure(list(height = c(69L, 44L, 72L, 58L), age = c(18L, 8L,
19L, 34L), dept = structure(c(1L, 2L, 2L, 3L), .Label = c("A",
"B", "C"), class = "factor")), row.names = c(NA, -4L), class = "data.frame")
推荐阅读
- python - 如何在 ipython 笔记本的整行中提取一些特定值
- c - 使用 Visual Studio 将 char 数组写入文件的正确语法是什么?
- r - 根据列条件将字符串粘贴到值
- postgresql - 数组和 tstzrange 的索引
- python - 如何根据内部元素值拆分元组列表
- c# - Bind DataGridView with FK (Master-Slave architecture), but allowing column customization at VS Editor (C# - Winform)
- java - 遵循 Spring MVC 指南,但模板文字值无法正确显示?
- javascript - PHP/Javascript 动态选择选项 - 如何处理选择选项文本中的撇号问题
- javascript - 如何动态更改输入背景颜色?
- python - 如何使用python在sqlite3中插入字典