【发布时间】:2021-04-08 03:35:24
【问题描述】:
我有一个日周期数据框,我将其转换为月周期,包括基于汇总值的简单转换:
tibble(
date = ymd("2002-12-31") + c(0:60),
index = 406 * exp(cumsum(rnorm(61,0,0.01)))
) %>% mutate(
year = year(date),
month = month(date)
) %>% group_by(year, month) %>% summarise(
date = last(date),
month.close = last(index),
) %>% mutate(
month.change = log(month.close / lag(month.close))
)
代码看起来很简单,但是当我运行它时,我得到了一些奇怪的东西:
`summarise()` regrouping output by 'year' (override with `.groups` argument)
# A tibble: 4 x 5
# Groups: year [2]
year month date month.close month.change
<dbl> <dbl> <date> <dbl> <dbl>
1 2002 12 2002-12-31 403. NA
2 2003 1 2003-01-31 419. NA
3 2003 2 2003-02-28 422. 0.00572
4 2003 3 2003-03-01 417. -0.0121
尽管第 1 行和第 2 行具有有效的 month.close 值,为什么第 2 行没有 month.change 值? summarise() 操作是否分别在两个给定维度上起作用?
我真的需要了解为什么会发生这种行为,所以请不要只是告诉我使用不同的函数来折叠周期性,我真的很想知道我实现的哪一部分我理解不正确,所以我以后不会在其他地方插入类似的错误。我知道这与按 2 个变量分组有关,因为当我将两列简化为一列时,我得到了预期的行为。
这段代码:
library(zoo)
tibble(
date = ymd("2002-12-31") + c(0:60),
index = 406 * exp(cumsum(rnorm(61,0,0.01)))
) %>% mutate(
year.month = as.yearmon(date)
) %>% group_by(year.month) %>% summarise(
date = last(date),
month.close = last(index),
) %>% mutate(
month.change = log(month.close / lag(month.close))
)
返回预期结果
`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 4 x 4
year.month date month.close month.change
<yearmon> <date> <dbl> <dbl>
1 Dec 2002 2002-12-31 405. NA
2 Jan 2003 2003-01-31 428. 0.0560
3 Feb 2003 2003-02-28 421. -0.0173
4 Mar 2003 2003-03-01 423. 0.00513
我错过了什么?
【问题讨论】: