“$ 运算符对于原子向量无效”错误如何解决?

问题描述 投票:0回答:1

我正在尝试使用贝叶斯 GLM 执行 CAPM 回归分析。我已经开发了下面的 R 代码,但是当我尝试拟合模型进行后验预测检查时,我得到了

posterior_intercept <- fitted(model_capm)$Estimate[1,]
。我尝试将创建的变量
Error in fitted(model_capm)$Estimate:$ operator is invalid for atomic vectors
转换为数据框,因为它已创建为
model_capm
但没有成功。
我正在尝试获得此输出:

这是错误行之前的代码:

Large brmsfit


r vector glm bayesian brms
1个回答
0
投票
library(ggplot2) library(dplyr) library(brms) library(bayesplot) set.seed(42) size <- 200 Rf <- 0.02 ERm <- 0.1 beta <- 1.5 sigma <- 0.05 ERm_samples <- rnorm(size, ERm, sigma) epsilon <- rnorm(size, 0, sigma) ERi_samples <- Rf + beta * (ERm_samples - Rf) + epsilon market_excess_return <- ERm_samples - Rf asset_excess_return <- ERi_samples - Rf data_capm <- data.frame(market_excess_return=market_excess_return, asset_excess_return=asset_excess_return) ggplot(data_capm, aes(x=market_excess_return, y=asset_excess_return)) + geom_point(aes(color='Sampled Data')) + labs(x='Market Excess Return', y='Asset Excess Return', title='Generated CAPM Data') + theme_minimal() # Bayesian regression using brms model_capm <- brm(asset_excess_return ~ market_excess_return, data = data_capm, family = gaussian(), prior = c( prior(normal(0, 20), class = Intercept), prior(normal(0, 20), class = b), prior(cauchy(0, 10), class = sigma) )) # Plotting the trace trace_capm <- as.mcmc(model_capm) bayesplot::mcmc_trace(trace_capm) # Posterior predictive checks posterior_intercept <- fitted(model_capm)$Estimate[1,] posterior_slope <- fitted(model_capm)$Estimate[2,] posterior_intercept <- fitted(model_capm)[1, "Estimate"] posterior_slope <- fitted(model_capm)[2, "Estimate"] x_plot <- seq(min(market_excess_return), max(market_excess_return), length.out = 100) ggplot(data_capm, aes(x=market_excess_return, y=asset_excess_return)) + geom_point(alpha=0.5) + geom_abline(intercept=mean(posterior_intercept), slope=mean(posterior_slope), color="blue", linetype="dashed") + labs(x='Market Excess Return', y='Asset Excess Return', title='Posterior Predictive Regression Lines with Observed Data') + theme_minimal()

检索数据,或者尝试将对象转换为数据框(或 tibble,我的偏好,使用

[]
)。这里:
as_tibble()

这应该可以让您访问所有后验分布
再说一遍,您始终可以访问 
fitted_ <- fitted(model_capm) class(fitted_) as_tibble(fitted_)

等..

最后,您只需通过环境按下模型对象即可查看其结构。当您将鼠标悬停在右侧时,您会看到一个按钮,如果单击它,它将粘贴在控制台中调用该对象的方法

© www.soinside.com 2019 - 2024. All rights reserved.