r - 使用 forcats 将因子折叠成组时出现错误
问题描述
我有以下数据框:
df = data.frame(a = 1:5) %>% as_tibble()
我想将值 1 和 3 折叠为“group1”,将 2 和 4 折叠为“group2”,将其他值(例如 5)折叠为“Other”。我认为 fct_collapse() 将是完美的功能,但它会做一些奇怪的事情......
df %>%
mutate(
a = as.character(a),
a_collapse = fct_collapse(a,
group1=c('1', '3'),
group2 = c('2', '4'),
group_other = TRUE))
然而,值 3 得到了 'group2' 而不是 'group1'。你知道为什么会这样吗?我想这与我的因子的值是数字但没有找到处理它的方法有关。任何的想法?
有些帖子处理类似的问题,但在这种情况下对我没有帮助:
解决方案
一个简单的case_when
?
library(dplyr)
df %>%
mutate(a_collapse = factor(case_when(a %in% c(1, 3)~"group1",
a %in% c(2, 4) ~"group2",
TRUE ~ 'Other')))
# A tibble: 5 x 2
# a a_collapse
# <int> <fct>
#1 1 group1
#2 2 group2
#3 3 group1
#4 4 group2
#5 5 Other
就fct_collapse
问题而言,这个问题似乎来自于在 Github 上的这个问题group_other
中引用的内容。如果我们删除它,它会按预期工作,但不会给其他组带来任何价值。
df %>%
mutate(
a = as.character(a),
a_collapse = forcats::fct_collapse(a,
group1=c('1', '3'),
group2 = c('2', '4')))
# A tibble: 5 x 2
# a a_collapse
# <chr> <fct>
#1 1 group1
#2 2 group2
#3 3 group1
#4 4 group2
#5 5 5
此错误已在开发版本中修复,forcats
并将在下一个版本中提供。
推荐阅读
- c# - 如何使用 AJAX 调用 ASP.NET 根页面中的 Web 方法
- c# - 将数据插入 SQL 表显示错误
- c++ - 将十六进制的 std::string 转换为 std::array
- vue.js - 模型值未更新 vue.js laravel 5.8 中复选框的 UI
- angular - Angular 6 应用程序从外部调用应用程序读取参数
- mysql - 具有许多大数组的单表与许多表
- oop - 在这种情况下,依赖倒置如何工作?
- python - 在 django 中创建弹出消息
- scala - 在 1 秒的窗口中获取第 1000 毫秒的数据
- jquery - jQuery - 具有多个 div 和附加隐藏功能的简单 slideToggle