如何最好地计算r的一年差异

发布于 2025-02-12 10:11:14 字数 618 浏览 3 评论 0原文

以下是示例代码。手头的任务是仅在第四季度创建一年差异(2021 Q4值-2020 Q4值)和百分比差异。所需的结果在下面。通常我会做一个pivot_wider等。但是,如何做到这一点,而不考虑所有季度?

  year <- c(2020,2020,2020,2020,2021,2021,2021,2021,2020,2020,2020,2020,2021,2021,2021,2021)
  qtr <- c(1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4)
  area <- c(1012,1012,1012,1012,1012,1012,1012,1012,1402,1402,1402,1402,1402,1402,1402,1402)
  employment <- c(100,102,104,106,108,110,114,111,52,54,56,59,61,66,65,49)

  test1 <- data.frame (year,qtr,area,employment)

  area       difference     percentage
  1012           5              4.7%
  1402           -10            -16.9

Below is the sample code. The task at hand is to create a year over year difference (2021 q4 value - 2020 q4 value) for only the fourth quarter and percentage difference. Desired result is below. Usually I would do a pivot_wider and such. However, how does one do this and not take all quarters into account?

  year <- c(2020,2020,2020,2020,2021,2021,2021,2021,2020,2020,2020,2020,2021,2021,2021,2021)
  qtr <- c(1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4)
  area <- c(1012,1012,1012,1012,1012,1012,1012,1012,1402,1402,1402,1402,1402,1402,1402,1402)
  employment <- c(100,102,104,106,108,110,114,111,52,54,56,59,61,66,65,49)

  test1 <- data.frame (year,qtr,area,employment)

  area       difference     percentage
  1012           5              4.7%
  1402           -10            -16.9

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深空失忆 2025-02-19 10:11:15

您将在季度使用过滤器

test1 |>
  filter(qtr == 4) |>
  group_by(area) |>
    mutate(employment_lag = lag(employment),
           diff = employment - employment_lag) |>
    na.omit() |>
  ungroup() |>
  mutate(percentage = diff/employment_lag)

输出:

# A tibble: 2 × 7
   year   qtr  area employment  diff employment_start percentage
  <dbl> <dbl> <dbl>      <dbl> <dbl>            <dbl>      <dbl>
1  2021     4  1012        111     5              106     0.0472
2  2021     4  1402         49   -10               59    -0.169 

更新:添加正确的百分比。

You would use filter on quarter:

test1 |>
  filter(qtr == 4) |>
  group_by(area) |>
    mutate(employment_lag = lag(employment),
           diff = employment - employment_lag) |>
    na.omit() |>
  ungroup() |>
  mutate(percentage = diff/employment_lag)

Output:

# A tibble: 2 × 7
   year   qtr  area employment  diff employment_start percentage
  <dbl> <dbl> <dbl>      <dbl> <dbl>            <dbl>      <dbl>
1  2021     4  1012        111     5              106     0.0472
2  2021     4  1402         49   -10               59    -0.169 

Update: Adding correct percentage.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文