R:创建从分类变量基于连续变量的新的分类变量

问题描述 投票:0回答:1

我已经有了一看here,其中使用cut功能。但是,我一直没能拿出给我的情况聪明的解决方案。

首先是一些示例数据,我目前有:

df <- data.frame(Category = LETTERS[1:20]
                 , Nber_within_category = c(rep(1,8), rep(2,3), rep(6,2), rep(10,3), 30, 50, 77, 90)
                 )

我想就形成基础上,Nber_within_category列一个新的类别第三列。在这个例子中,我怎么能做出如Category_new使得在每个类别中,Nber_within_category是至少5,如果Category已有Nber_within_category >= 5,原始类别采取的约束。

因此,例如,它应该是这样的:

df <- data.frame(Category = LETTERS[1:20]
                 , Nber_within_category = c(rep(1,8), rep(2,3), rep(6,2), rep(10,3), 30, 50, 77, 90)
                 , Category_new = c(rep('a',5), rep('b', 4), rep('c',2), LETTERS[12:20])
)
r variables split categories
1个回答
1
投票

这是一个黑客攻击的一位,但它的工作原理:

df %>% 
  mutate(tmp = floor((cumsum(Nber_within_category) - 1)/5)) %>% 
  mutate(new_category = ifelse(Nber_within_category >= 5,
                               Category,
                               letters[tmp+1]))

该生产线floor((cumsum(Nber_within_category) - 1)/5)是大小5箱(-1至包括其中的总和正好是5行)的分类的cumsum的方式,和我使用的指标即得到该行,其中Nber_within_category < 5新的类别

它可能会更容易理解列tmp是如何定义的,如果你运行:

x <- 1:100
data.frame(x, y = floor((x- 1)/5))
© www.soinside.com 2019 - 2024. All rights reserved.