当自变量日期不连续时如何使用 lmer 运行循环

问题描述

我以这种方式构建了数据,之前询问如何将其转换为长格式并保持日期不变。回答对我帮助很大,但现在我之前用它运行的模型运行良好,不起作用。

这是我得到的错误

Ops.Date(day,j) 中的错误:/ 未为“日期”对象定义。

现在,它在运行循环后立即停止工作

Symbol   Name    X2020.01.02 X2020.01.03 X2020.01.06 X2020.01.07 X2020.01.08 X2020.01.09 
1   AAPL  Apple     75.0875     74.3575       74.95     74.5975     75.7975     77.4075     
2   ABBV AbbVie     89.5500     88.7000       89.40     88.8900     89.5200     90.2100 

这是我运行的代码行。我该怎么做才能让我的模型仍然有效?

tempDataLong <- data_2020 %>%
    pivot_longer(cols = starts_with('X'),names_to = 'day',names_pattern = 'X(.*)') %>%
    mutate(day = lubridate::ymd(day))
  
  class(tempDataLong$day)

  
  # Define dates for analysis and prediction
    nDays<- 7
    end_date = max(tempDataLong$day)
    start_date= end_date-6
    predict_date = end_date+ nDays

  
  #1.7 create all the variables for the loop process and model comparison
  
  
  max_sin  = 100    # The highest cycle I'll search within
  bic_value = rep(NA,max_sin) # BIC vector
  model_value= rep(NA,max_sin) #model comparison vector
  
     # For each degree
      for (j in seq(5,max_sin,5)) {
      
      
      #create the statistical model to predict
        max_sin <- lmer(close ~ sin(day/j)* day + (1|Symbol),data= tempDataLong) 

      
      # Save the BIC value
      bic_value[j/5] = BIC(max_sin)
      
      model_value[j/5]= paste("model used is  of cycle",j)
      
      }
      
      #create data frame of both the model index and the BIC value for that model 
      bic_model<- data.frame( model_value= model_value,bic_value=bic_value)
      
      #For documentation purposes: Find the model with the minimal BIC
      #best_model <- model_value[which.min(bic_model$bic_value)]
      
      #Find the model with the minimal BIC
      chosen_model<- lmer(close ~ sin(day/(which.min(bic_model$bic_value)*5))* day + (1|Symbol),data= tempDataLong) 
       
      #create the the data frame for prediction values
      newdata <- data.frame(Symbol = data_2020$Symbol,Symbol = data_2020$Name,day= predict_date)
     
     #Predict closing values 
     predicted_data<- data.frame(Symbol = data_2020$Symbol,Name = data_2020$Name,predicted_value= round(predict(chosen_model,newdata),2))

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)