使用dplyr的铅和滞后问题

发布于 2025-01-30 11:59:21 字数 576 浏览 1 评论 0原文

我有一个数据框架,其中有365行反映日历年的数据。我试图将县名列转换为一排。数据框架不包含任何缺失的值。

我尝试使用以下代码将其移动,但是结果表的值全是Na。

covid_shift <- covid_pivot %>% 
mutate(Maricopa = lag(Maricopa), Cook = lag(Cook), Harris = lag(Harris))

有人知道可能是什么问题吗?

I have a data frame with data that looks like this that has 365 rows reflecting the calendar year. I am trying to shift the county name columns up by one row. The data frame doesn't contain any missing values.

enter image description here

I tried using the following code to shift it, but the resulting table has values that are all NA.

covid_shift <- covid_pivot %>% 
mutate(Maricopa = lag(Maricopa), Cook = lag(Cook), Harris = lag(Harris))

enter image description here

Does anyone know what might be the issue?

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

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

发布评论

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

评论(1

贱贱哒 2025-02-06 11:59:21

由于covid_pivot按日期分组,并且每个组中的每一组都有一行,因此铅和滞后​​函数返回na。

尝试:

covid_shift <- covid_pivot %>%
  ungroup() %>%
  mutate(Maricopa = lag(Maricopa), Cook = lag(Cook), Harris = lag(Harris))

您还可以考虑使用()使用

covid_pivot %>%
  ungroup() %>%
  mutate(across(-date, ~lag(.x)))

Since covid_pivot is grouped by date, and each of these groups has one row, the lead and lag functions return NA.

Try:

covid_shift <- covid_pivot %>%
  ungroup() %>%
  mutate(Maricopa = lag(Maricopa), Cook = lag(Cook), Harris = lag(Harris))

You might also consider using across()

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