gpt4 book ai didi

r - 在 groupby 中分配楼层日期失败

转载 作者:行者123 更新时间:2023-12-02 00:54:41 26 4
gpt4 key购买 nike

这是我的代码,我对 groupby 有疑问:

    library(dplyr)
library(lubridate)

df <- read.xlsx("Data.xlsx", sheet = "Sector-STOXX600", startRow = 2,colNames = TRUE, detectDates = TRUE, skipEmptyRows = FALSE)
df[2:19] <- data.matrix(df[2:19])


percent_change2 <- function(x)last(x)/first(x) - 1

monthly_return <- df %>%
group_by(gr = floor_date(Date, unit = "month")) %>%
summarize_at(vars(-Date, -gr), percent_change2) %>%
ungroup() %>%
select(-gr) %>%
as.matrix()

确实我有这个错误:

"Error in is_character(x) : object 'gr' not found"

这是数据集的示例:

    Date  .SXQR  .SXTR  .SXNR  .SXMR  .SXAR  .SX3R  .SX6R  .SXFR  .SXOR  .SXDR  .SX4R  .SXRR  .SXER
1 2000-01-03 364.94 223.93 489.04 586.38 306.56 246.81 385.36 403.82 283.78 455.39 427.43 498.08 457.57
2 2000-01-04 345.04 218.90 474.05 566.15 301.13 239.24 374.64 390.41 275.93 434.92 414.10 476.17 435.72

更新

volatility_function<- function(x)sqrt(252) * sd(diff(log(x))) * 100
annualized_volatility <- df %>%
mutate(Date=ymd(Date)) %>%
group_by(gr = floor_date(Date, unit = "year")) %>%
select(gr,everything()) %>%
summarize_at(vars(-Date, -gr), volatility_function) %>%
ungroup() %>% select(-gr) %>%
as.matrix()
head(annualized_volatility,5)

我尝试了@NeslonGon 告诉我的操作,但是我知道在另一个函数上出现了同样的错误,我应该怎么办?

最佳答案

我们的想法是,我们不需要summarise_at 分组变量,而是使用Date 来说明这一点。可以跳过 selectmutate 调用。他们是为了方便。

df %>%
mutate(Date=ymd(Date)) %>%
group_by(gr = floor_date(Date, unit = "month")) %>%
select(gr,everything()) %>%
summarize_at(vars(-Date), percent_change2) %>%
ungroup() %>%
select(-gr) %>%
as.matrix()

关于r - 在 groupby 中分配楼层日期失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55180081/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com