【发布时间】:2018-10-09 22:42:08
【问题描述】:
以下是我为 dplyr 编写的问题的表述:
library(tidyverse)
df <- tibble(State = c("A", "A", "A", "A", "A", "A", "B", "B", "B"),
District_code = c(1:9),
District = c("North", "West", "North West", "South", "East", "South East",
"XYZ", "ZYX", "AGS"),
Population = c(1000000, 2000000, 3000000, 4000000, 5000000, 6000000,
7000000, 8000000, 9000000))
df
#> # A tibble: 9 x 4
#> State District_code District Population
#> <chr> <int> <chr> <dbl>
#> 1 A 1 North 1000000
#> 2 A 2 West 2000000
#> 3 A 3 North West 3000000
#> 4 A 4 South 4000000
#> 5 A 5 East 5000000
#> 6 A 6 South East 6000000
#> 7 B 7 XYZ 7000000
#> 8 B 8 ZYX 8000000
#> 9 B 9 AGS 9000000
对于某些州,我需要将使用名称的地区合并到更少的地理类别中。特别是,A 国应该只有:“North - West - North West”和“South - East - South East”。必须添加一些变量,例如人口;但其他像 District_code 应该获得 NA。我发现了this example 的跨行操作,但并不完全相同。 Grouping 似乎不适用。
最终的结果应该是这样的:
new_df
#> # A tibble: 5 x 4
#> State District_code District Population
#> <chr> <int> <chr> <dbl>
#> 1 A NA North - West - North West 5000000
#> 2 A NA South - East - South East 15000000
#> 3 B 7 XYZ 7000000
#> 4 B 8 ZYX 8000000
#> 5 B 9 AGS 9000000
在实际数据框中,有许多变量(例如 Population)必须添加,还有一些其他变量(例如 District_code)必须获取 NA 值。
非常感谢您的帮助!
【问题讨论】: