如何修复错误?“$ operator对于原子向量无效”

rhfm7lfc  于 2023-06-03  发布在  其他
关注(0)|答案(1)|浏览(274)

为什么我甚至没有使用$符号时会出现以下错误?如何修复这个错误?
对象$coefficients中的错误:$运算符对于原子向量无效

> library(data.table)
> library(ggplot2)
> library(lmtest)
> library(sandwich)
> 

> load("C:/Users/apple/OneDrive/Desktop/data_assignment_2.RData")
> 
> # Subset the data for the desired time period
> data <- FBm[ym >= as.Date("1964-01-01") & ym <= as.Date("2003-12-31")]
> 
> # Calculate excess returns and lagged excess returns
> returns <- data$fb.y01
> rf <- as.numeric(data$ym)  # Convert rf to numeric
> excess_returns <- returns - rf
> lagged_excess_returns <- lag(excess_returns)
> 
> # OLS model
> ols_model <- lm(excess_returns ~ lagged_excess_returns)
> 
> # Newey-West (NW) model
> nw_model <- NeweyWest(ols_model, lag = 18)
Warning message:
In summary.lm(x) : essentially perfect fit: summary may be unreliable
> 

> data_plot <- data.frame(
+   "Maturity" = c(1, 2, 3, 4, 5),
+   "Coefficient" = c(coefficients(ols_model)[-1], coefficients(nw_model)[-1]),
+   "Model" = c(rep("OLS", length(coefficients(ols_model))-1), rep("NW", length(coefficients(nw_model))-1))
+ )

Error in object$coefficients : $ operator is invalid for atomic vectors
k7fdbhmy

k7fdbhmy1#

是因为

  • coefficients()函数调用coef()方法
  • NeweyWest()返回一个数值矩阵,该矩阵没有定义特定的coef()方法;和/或
  • stats:::coef.default()尝试访问object$coefficients

我不知道您希望coefficients(nw_model)返回什么,但您需要找到一种不同的方法来获得该结果(不管它是什么)

相关问题