我有全国每一次人口普查的三个时间点(2000年、2013年、2019年)的数据,这些数据按人口统计局分类。我正在尝试创建一个名为cont_chg_pedu_colplus的新变量,这是pedu_colplus 2013年和2000年值之间的差异。因此,在下面的示例中,我希望创建一个名为cont_chg_pedu_colplus的新列,该列返回的值为3.0 (14.6 - 11.6)。理想情况下,每组域都有相同的值,因为我只对时间1和时间2之间的差异感兴趣。
tractid year CBSA_name pedu_colplus
<chr> <dbl> <chr> <dbl>
1 48059030101 2000 Abilene, TX 11.6
2 48059030101 2013 Abilene, TX 14.6
3 48059030101 2019 Abilene, TX 20.6
4 48059030102 2000 Abilene, TX 11.6
5 48059030102 2013 Abilene, TX 14.2
6 48059030102 2019 Abilene, TX 20.2下面是我到目前为止的代码。它抛出了以下错误,我想是因为我只在一年(37行而不是数据集中的111行)上做了修改。我不想把我的数据写得太宽,因为我还有很多其他的数据操作要做。我不能推迟工作时间。
gent_vars_prelim <- outcome_data %>%
mutate(cont_chg_pedu_colplus = pedu_colplus[year == 2013] - pedu_colplus[year == 2000], na.rm = TRUE) %>%
glimpse()问题与
mutate()输入cont_chg_pedu_colplus。X输入cont_chg_pedu_colplus不能回收到37大小。输入cont_chg_pedu_colplus为pedu_colplus[year == 2013] - pedu_colplus[year == 2000]。cont_chg_pedu_colplus输入ℹ必须大小为37或1,而不是0。错误发生在第1组: CBSA_name = "Abilene,TX",年份=2000年
有什么想法吗?谢谢。
发布于 2021-04-21 04:15:11
我将假设,对于每一对唯一的tractid和CBSA_name,year最多有3个条目(可能值为2000年、2013年或2019年),对于给定的tractid和CBSA_name,没有两年是相同的。
首先,我们将通过tractid和CBSA_name对数据帧中的值进行分组。每组最多有3行,每年一排。我们用dplyr::group_by(tractid, CBSA_name)来做这件事。
接下来,我们将强迫该小组拥有全部3年的时间。正如您在评论中所建议的那样,我们使用tidyr::complete(year = c(2000, 2013, 2019))进行此操作。(这比我使用filter(n() == 3)的评论要好,因为如果2019年失踪,而且我们能够保存不完整的组,我们实际上不会在意。)
然后,我们可以计算您感兴趣的结果:dplyr::mutate(cont_chg_pedu_colplus = pedu_colplus[year == 2013] - pedu_colplus[year == 2000])。我们只需要dplyr::ungroup()在这之后,我们就结束了。
最终代码:
gent_vars_prelim <- outcome_data %>%
dplyr::group_by(tractid, CBSA_name) %>%
tidyr::complete(year = c(2000, 2013, 2019)) %>%
dplyr::mutate(cont_chg_pedu_colplus = pedu_colplus[year == 2013] - pedu_colplus[year == 2000]) %>%
dplyr::ungroup() %>%
glimpse()测试用例:
outcome_data <- data.frame(tractid = c(48059030101, 48059030101, 48059030101, 48059030101, 48059030101, 48059030101, 48059030102, 48059030102, 48059030102, 48059030103),
year = c(2000, 2013, 2019, 2000, 2013, 2019, 2000, 2013, 2019, 2000),
CBSA_name = c("Abilene, TX", "Abilene, TX", "Abilene, TX", "Austin, TX", "Austin, TX", "Austin, TX", "Abilene, TX", "Abilene, TX", "Abilene, TX", "Abilene, TX"),
pedu_colplus = c(11.6, 14.6, 20.6, 8.4, 9.0, 9.6, 11.6, 14.2, 20.2, 4.0))结果:
> tibble(gent_vars_prelim)
# A tibble: 12 x 1
gent_vars_prelim$tractid $CBSA_name $year $pedu_colplus $cont_chg_pedu_colplus
<dbl> <fct> <dbl> <dbl> <dbl>
1 48059030101 Abilene, TX 2000 11.6 3
2 48059030101 Abilene, TX 2013 14.6 3
3 48059030101 Abilene, TX 2019 20.6 3
4 48059030101 Austin, TX 2000 8.4 0.600
5 48059030101 Austin, TX 2013 9 0.600
6 48059030101 Austin, TX 2019 9.6 0.600
7 48059030102 Abilene, TX 2000 11.6 2.60
8 48059030102 Abilene, TX 2013 14.2 2.60
9 48059030102 Abilene, TX 2019 20.2 2.60
10 48059030103 Abilene, TX 2000 4 NA
11 48059030103 Abilene, TX 2013 NA NA
12 48059030103 Abilene, TX 2019 NA NA https://stackoverflow.com/questions/67188006
复制相似问题