gpt4 book ai didi

r - 子组的新列和另一列中的百分比范围

转载 作者:行者123 更新时间:2023-12-02 02:50:17 27 4
gpt4 key购买 nike

我有一个样本 df,如下所示:

df_test<- data.frame("Group.Name"=c("Group1","Group2","Group1","Group2","Group2","Group2","Group1"),
"Sub_group_name"=c("A","A","B","C","D","E","C"),
"Total%"=c(35,26,10,9,5,11,13))

原来的df比较大,关于这个df需要记住的几点:

  • 只有“Group1”和“Group2”两个组
  • 一个组下有多个子组,上面的df显示了部分子组
  • 组 + 子组的总百分比加起来为 100%。在上面不是,因为它只是一个示例。所以,对于 Group1所有子组,如 A, B, C等等将为“Group2”添加多达 100 等。 Group1Group2 的子组大致相同

提问:

我需要创建一个名为 Category 的列它可以在 Total% 范围内工作在 Group.Name 上等级。创建新列的条件是:

  • 对于每个 Group.Name无论在哪里Total%是最高的,类别列是Sub_group_name名字是。

  • 对于每个 Group.NameTotal%在 10-30 之间,类别列为“New_Group1”。

  • 对于每个 Group.NameTotal%小于 10,类别列为“New_Group2”。

预期输出:

df_output<- data.frame("Group.Name"=c("Group1","Group2","Group1","Group2","Group2","Group2","Group1"),
"Sub_group_name"=c("A","A","B","C","D","E","C"),
"Total%"=c(35,26,10,9,5,11,13),
"category"=c("A","A","New_Group1","New_Group1","New_Group2","New_Group1","New_Group1"))

最佳答案

我们可以使用 cut 来创建带有相应 breakslabels,然后替换“Total”。这是每个 'Group.Name' 中最高的,具有相应的 'Sub_group_name'

library(dplyr)
df_test %>%
group_by(Group.Name) %>%
mutate(category = as.character(cut(`Total%`, breaks = c(-Inf,10, 30, Inf),
labels = c("New_Group2", "New_Group1", "Other"), right = FALSE)),
category = case_when(`Total%` == max(`Total%`) ~
Sub_group_name,
TRUE ~ category))
# A tibble: 7 x 4
# Groups: Group.Name [2]
# Group.Name Sub_group_name `Total%` category
# <chr> <chr> <dbl> <chr>
#1 Group1 A 35 A
#2 Group2 A 26 A
#3 Group1 B 10 New_Group1
#4 Group2 C 9 New_Group2
#5 Group2 D 5 New_Group2
#6 Group2 E 11 New_Group1
#7 Group1 C 13 New_Group1

数据

df_test<- data.frame("Group.Name"=c("Group1","Group2","Group1","Group2","Group2",
"Group2","Group1"),
"Sub_group_name"=c("A","A","B","C","D","E","C"),
"Total%"=c(35,26,10,9,5,11,13), stringsAsFactors = FALSE,
check.names = FALSE)

关于r - 子组的新列和另一列中的百分比范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52521310/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com