微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决当自变量日期不连续时如何使用 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 举报,一经查实,本站将立刻删除。