简体   繁体   English

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

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

I want to create an area group according to the areacode.我想根据区号创建一个区域组。 By doing this, all area_g becomes A. Only codes 50110250, 50110253, 50110310 should be A!通过这样做,所有 area_g 都变为 A。只有代码 50110250、50110253、50110310 应该是 A! and 50110101~50110140 should be 'B'.和 50110101~50110140 应该是“B”。 what's wrong... This is the code I wrote.怎么了...这是我写的代码。 Thank you.谢谢你。

     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")))))))   

As mentioned in the comments:如评论中所述:

  1. it's best to avoid nesting ifelse functions, because dplyr::case_when() is more legible and less error-prone最好避免嵌套ifelse函数,因为dplyr::case_when()更易读且不易出错
  2. the %in% operator will assess whether the left-hand side is present in the vector on the right hand-side. %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

Created on 2022-06-24 by the reprex package (v2.0.1)reprex 包(v2.0.1)于 2022 年 6 月 24 日创建

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

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