繁体   English   中英

根据统计程序R中的区号对区域进行分组

[英]Grouping regions according to area codes in statistical program R

我想根据区号创建一个区域组。 通过这样做,所有 area_g 都变为 A。只有代码 50110250、50110253、50110310 应该是 A! 和 50110101~50110140 应该是“B”。 怎么了...这是我写的代码。 谢谢你。

     AAA <- AAA %>%
  
      mutate(AAA, area_g = ifelse(areacode==50110250|50110253|50110310, "A",
                              ifelse(areacode==50110101:50110140, "B",
                               ifelse(areacode==50110256|50110253, "C",
                                ifelse(areacode==50130250|50130310, "D",
                                 ifelse(areacode==50130101:50130122, "E",
                                  ifelse(areacode==50130253|50130259|50130320, "F")))))))   

如评论中所述:

  1. 最好避免嵌套ifelse函数,因为dplyr::case_when()更易读且不易出错
  2. %in%运算符将评估左侧是否存在于右侧的向量中。
library(dplyr)
# Simulate data
AAA <- data.frame(areacode = 0:10)

AAA |> 
  mutate(area_g = case_when(areacode == 0 ~ "A",
                            areacode %in% 1:3 ~ "B",
                            areacode == 4 ~ "C",
                            areacode %in% 5:7 ~ "D",
                            TRUE ~ "E"))
#>    areacode area_g
#> 1         0      A
#> 2         1      B
#> 3         2      B
#> 4         3      B
#> 5         4      C
#> 6         5      D
#> 7         6      D
#> 8         7      D
#> 9         8      E
#> 10        9      E
#> 11       10      E

reprex 包(v2.0.1)于 2022 年 6 月 24 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM