是否可以在R中同时运行两个while循环?

时间:2019-07-03 12:25:38

标签: r while-loop functional-programming

我有两个使用while循环的函数,希望将它们组合在一起,以便两个循环同时运行。第一个功能/循环使用户可以使用数字键1到5交互地将数据输入到控制台,而第二个功能/循环则显示倒数计时器,以告知用户实验还剩下多长时间。我希望能够同时开始实验和倒计时。

我已经尝试将两个功能合并为一个功能,但未成功:

record_data = function(x) {
require(tictoc) #load required package
require(tcltk)

time_period = readline("Length of observation period (mins): ") # requires user input
  time_period = as.numeric(time_period)

  pb <- tkProgressBar("Timer")
  start = Sys.time()

while(T){       #open infinite while loop
    tic()       #start timer
    elapsed = as.numeric(difftime(Sys.time(), start, units = 'mins'))
    remaining = time_period - elapsed
    Sys.sleep(0.1)
    setTkProgressBar(pb,
                     remaining / time_period,
                     label = sprintf("Time remaining: %i min", round(remaining)))
    if (remaining <= 0)
      break

    input_state=readline("State input: ")  #allow for entry of state
    if(input_state %in% 1:5){    #check if it's acceptable 
        elapsed=toc()            #if it is then end timer and record data
        write.table(cbind(input_state,elapsed$toc-elapsed$tic),'results.txt',col.names=F,row.names=F,quote=F,append=T)
    }else if(input_state=='t'){  #if input is 't' 
        break                    #break out of while loop
    }else if(input_state <1 | input_state > 5 & input_state!='t'){#if input is not and accepted state AND is not 't'
     print('thats not an allowed state- please try another')
     } 
  }
  Sys.sleep(2)
  close(pb)

}

功能一(在控制台中通过用户输入来收集数据):

record_data = function(x) {
require(tictoc) #load required package
while(T){       #open infinite while loop
    tic()       #start timer
    input_state=readline("State input: ")  #allow for entry of state
    if(input_state %in% 1:5){    #check if it's acceptable 
        elapsed=toc()            #if it is then end timer and record data
        write.table(cbind(input_state,elapsed$toc-elapsed$tic),'results.txt',col.names=F,row.names=F,quote=F,append=T)
    }else if(input_state=='t'){  #if input is 't' 
        break                    #break out of while loop
    }else if(input_state <1 | input_state > 5 & input_state!='t'){#if input is not and accepted state AND is not 't'
     print('thats not an allowed state- please try another')
     } 
  }
}

功能二(用于倒计时实验的计时器):

timer = function(x) {
  require(tcltk)
  time_period = readline("Length of observation period (mins): ")
  time_period = as.numeric(time_period)

  pb <- tkProgressBar("Timer")
  start = Sys.time()
  while (TRUE) {
    elapsed = as.numeric(difftime(Sys.time(), start, units = 'mins'))
    remaining = time_period - elapsed
    Sys.sleep(0.1)
    setTkProgressBar(pb,
                     remaining / time_period,
                     label = sprintf("Time remaining: %i min", round(remaining)))
    if (remaining <= 0)
      break
  }
  Sys.sleep(2)
  close(pb)

我的尝试显然没有用,并且我不确定如何解决问题。我希望函数部署一个在收集数据时自动开始的计时器。谢谢。

0 个答案:

没有答案