Print Only When Condition is True in R

家住魔仙堡 提交于 2021-01-05 04:48:15

问题


This solution Automate Seed as a Vector Instead of an Integer in R

library(forecast)
SEED_vector <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19)
arima_order_results = data.frame()
for (my_seed in SEED_vector){
  set.seed(my_seed)
  ar1 <- arima.sim(n = 10, model=list(ar=0.2, order = c(1, 0, 0)), sd = 1)
  ar2 <- auto.arima(ar1, ic ="aicc")

  arima_order = arimaorder(ar2)
  arima_order = t(as.data.frame(arima_order))
  # Print the arima order.
  print(arima_order)
  # This line of code is just if you want to store the results in a dataframe
  arima_order_results = rbind(arima_order_results,arima_order)
}

I will only want arimaorder of (1, 0, 0) to be printed instead of all

I tried this and jammed with error:

SEED_vector <- 1:100
arima_order_results <- data.frame()
while(TRUE){for (my_seed in SEED_vector) {set.seed(my_seed)
    ar1 <- arima.sim(n = 10, model=list(ar=0.2, order = c(1, 0, 0)), sd = 1)
    ar2 <- auto.arima(ar1, ic ="aicc")
    if(all(arimaorder(ar2)==c(1,0,0))) print(arima_order_results)
    arima_order = arimaorder(ar2)
    arima_order = t(as.data.frame(arima_order))
    # Print the arima order.
    print(arima_order)
    # This line of code is just if yo uwant to store the results in a dataframe
    arima_order_results = rbind(arima_order_results,arima_order)

}}

I want something like this:

#arima_order14 1 0 0 
#arima_order39 1 0 0 
#arima_order47 1 0 0 

回答1:


Perhaps, this helps

SEED_vector <- 1:200
arima_order_results <- data.frame()
flag <- TRUE
i <- 1
seed_out <- c()
while(flag){ 
 
     set.seed(SEED_vector[i])
     ar1 <- arima.sim(n = 10, model=list(ar=0.2, order = c(1, 0, 0)), sd = 1)
     ar2 <- auto.arima(ar1, ic ="aicc")
     if(all(arimaorder(ar2)==c(1,0,0))) {
     
        #print(arima_order_results)
        print(paste0('arimaorder', SEED_vector[i], ' ' , 
              paste(arimaorder(ar2), collapse=" ")))
         seed_out <- c(seed_out, SEED_vector[i])
        
        }
       
     arima_order = arimaorder(ar2)
     arima_order = t(as.data.frame(arima_order))
     
     
     arima_order_results = rbind(arima_order_results,arima_order)
     
     i <- i+1
     if(i == length(SEED_vector)) {
     
      flag <- FALSE
     }

 }

-output

#[1] "arimaorder14 1 0 0"
#[1] "arimaorder152 1 0 0"
#[1] "arimaorder165 1 0 0"

Now, we check the vector

seed_out
#[1]  14 152 165

and it can be written to a file with write.table or cat

cat(seed_out, file = 'seed_file.txt')


来源:https://stackoverflow.com/questions/65270719/print-only-when-condition-is-true-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!