如何修复错误?“$ 运算符对原子向量无效”

How to fix the error? "$ operator is invalid for atomic vectors"

提问人:user20396712 提问时间:5/27/2023 最后编辑:user20396712 更新时间:5/27/2023 访问量:216

问:

为什么当我甚至不使用 $ 符号时会出现以下错误?以及如何解决此错误?

object$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
R 错误处理 语法错误

评论


答:

2赞 Ben Bolker 5/27/2023 #1

因为

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

我不知道你到底想返回什么,但你需要想出一种不同的方法来获得这个结果(不管它是什么)coefficients(nw_model)