我在R编程方面相当新颖,想要获取键盘输入来执行更多编程代码。 当执行这里给出的代码时,一切都很好,但是当输入退出时,程序终止并且它不打印y和z 。
你能告诉我如何在循环中使用readline命令并在该循环后执行其他程序行吗?
n=1 a=1 y=c() z=c() x="" while(x!="exit"){ x<-readline("Enter your name ") library(stringr) if(x!="exit" & str_detect(x,"N")){ y[n]=x n=n+1 }else{ z[a]=x a=a+1 } } print(y) print(z)I am fairly new in R programming and want to grab keyboard entry to execute further programming codes. As the code as given here is executed, everything works all good but when the exit is entered the program is terminated and it didn't print y and z.
Could you please advise me how to use readline command in loop and execute other program lines after that loop?
n=1 a=1 y=c() z=c() x="" while(x!="exit"){ x<-readline("Enter your name ") library(stringr) if(x!="exit" & str_detect(x,"N")){ y[n]=x n=n+1 }else{ z[a]=x a=a+1 } } print(y) print(z)最满意答案
此代码有效。 我已经将它复制到foo.R文件中,如下所示:
# in "foo.R" n = 1 a = 1 y = character() z = character() x = "" library(stringr) while (x!="exit") { x <- readline("Enter your name\n") if (x!="exit" & str_detect(x,"N")) { y[n] = x n = n+1 } else { z[a] = x a = a+1 } } print(y) print(z)然后,从我的R控制台(具有适当的工作目录),我可以运行:
source("foo.R") # Enter your name # Bob # Enter your name # Nate # Enter your name # exit # [1] "Nate" # [1] "Bob" "exit"它似乎工作得很好。
This code works. I have copied it in a foo.R file as so :
# in "foo.R" n = 1 a = 1 y = character() z = character() x = "" library(stringr) while (x!="exit") { x <- readline("Enter your name\n") if (x!="exit" & str_detect(x,"N")) { y[n] = x n = n+1 } else { z[a] = x a = a+1 } } print(y) print(z)And then, from my R console (with the proper working directory), I can run :
source("foo.R") # Enter your name # Bob # Enter your name # Nate # Enter your name # exit # [1] "Nate" # [1] "Bob" "exit"and it seems to work just fine.
更多推荐
发布评论