我是 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
我的目标是了解 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
我可以在这里实现我的输出。但是我如何在过滤器中添加 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
最佳答案
如果我没理解错的话,你可以将 group_by(Zip)
替换为 group_by(Zip, City)
df %>%
filter(Year %in% c(2015,2017)) %>%
spread(Year, Total_Population) %>%
group_by(Zip, City) %>%
summarise(
Total2015 = sum(2015, na.rm = TRUE),
Total2017 = sum(2017, na.rm = TRUE)) %>%
mutate(Difference = Total2017 - Total2015)
## A tibble: 2 x 5
## Groups: Zip [2]
# Zip City Total2015 Total2017 Difference
# <fct> <fct> <dbl> <dbl> <dbl>
#1 ZCTA5 00601 Adjun 2015 2017 2
#2 ZCTA5 00602 Agua 2015 2017 2
示例数据
df <- read.table(text =
"Zip Year Total_Population Median_Income City State
'ZCTA5 00601' 2015 18088 10833 Adjun PR
'ZCTA5 00602' 2017 40859 16353 Agua AB", header = T)
关于r - 为什么 dplyr::filter 不允许我过滤两个垂直方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55390706/