为什么dplyr :: filter不允许我使用两个垂直方向进行过滤?

5 r dplyr

我是R的新手,正在从事一个项目。

data.frame acscleantib的表格如下

head(acscleantib[-3])

#       Zip        Year Total_Population Median_Income City  State                                    
#    ZCTA5 00601    2015      18088         10833    Adjun   PR    
#      ZCTA5 00602  2017      40859         16353    Agua    AB
Run Code Online (Sandbox Code Playgroud)

我的目标是了解2015年与2017年之间总人口的差异。

我的输入:

popuinc <-  acscleantib %>% dplyr::filter(Year %in% c(2015,2017)) %>% 
    spread(Year,Total_Population) %>% group_by(Zip) %>%
    summarise(`Total2015` = sum(`2015`, na.rm = TRUE),
            `Total2017` = sum(`2017`, na.rm = TRUE)) %>% 
    mutate(Difference = Total2017- Total2015)

popuinc

#    Zip       Total2015 Total2017 Difference
#  <fct>           <int>     <int>      <int>
#1 ZCTA5 00601     17982     17599       -383
#2 ZCTA5 00602     40260     39209      -1051
#3 ZCTA5 00603     52408     50135      -2273
Run Code Online (Sandbox Code Playgroud)

我可以在这里实现我的输出。但是,如何添加City过滤器以便与各个城市一起获得最终的突变?

所需的输出示例:

 Zip          Total2015 Total2017  Difference City
   <fct>           <int>     <int>      <int>
 1 ZCTA5 00601     17982     17599       -383    Adjunitas
 2 ZCTA5 00602     40260     39209      -1051    XYZ
 3 ZCTA5 00603     52408     50135      -2273    etc
Run Code Online (Sandbox Code Playgroud)