2012-08-07 199 views
0

我对R有点新,并且对我正在编写的程序有疑问。我希望能够用一个while循环(最终使用每个read.table)接收文件(与用户一样多),但它一直在打断我。 这是我到目前为止有:R:虽然循环输入

cat("Please enter the full path for your files, if you have no more files to add enter 'X': ") 
fil<-readLines(con="stdin", 1) 
cat(fil, "\n") 
while (!input=='X' | !input=='x'){ 
inputfile=input 
input<- readline("Please enter the full path for your files, if you have no more files to add enter 'X': ") 
} 
if(input=='X' | input=='x'){ 
exit -1 
} 

当我运行它(从命令行(UNIX))我得到这些结果:

> library("lattice") 
> 
> cat("Please enter the full path for your files, if you have no more files to add enter 'X': ") 
Please enter the full path for your files, if you have no more files to add enter 'X': > fil<-readLines(con="stdin", 1) 
x 
> cat(fil, "\n") 
x 
> while (!input=='X' | !input=='x'){ 
+ inputfile=input 
+ input<- readline("Please enter the full path for your files, if you have no more files to add enter 'X': ") 
+ } 
Error: object 'input' not found 
Execution halted 

我不太知道如何解决这个问题,但我很确定这可能是一个简单的问题。 有什么建议吗? 谢谢!

+1

@ttmaccer:您应该将其写为答案 – 2012-08-07 14:31:32

+0

您可以尝试使用'choose.files' – James 2012-08-07 14:33:27

+0

@James您是否知道我可以找到如何使用choose.file的示例的地方? – Stephopolis 2012-08-07 14:34:55

回答

3

当你第一次运行脚本输入不存在。指定

input<-c() 

您while语句之前说还是把 inputfile=input 下面input<- readline....

+0

非常感谢!我知道这将是一个非常愚蠢的问题,但我很困扰它。 – Stephopolis 2012-08-07 14:36:10

1

我不太确定的根本问题是什么,您的问题。可能是因为你输入的目录路径不正确。

这是我用过几次的解决方案。它使用户更容易。基本上,您的代码不需要用户输入,它只需要为文件命名。

setwd("Your/Working/Directory") #This doesn't change 
filecontents <- 1 
i <- 1 
while (filecontents != 0) { 
    mydata.csv <- try(read.csv(paste("CSV_file_",i,".csv", sep = ""), header = FALSE), silent = TRUE) 
    if (typeof(mydata.csv) != "list") { #checks to see if the imported data is a list 
     filecontents <- 0 
    } 
    else { 
     assign(paste('dataset',i, sep=''), mydata) 
     #Whatever operations you want to do on the files. 
     i <- i + 1 
    } 
} 

正如你所看到的,对于这些文件的命名约定是CSV_file_n其中n是任意数量的输入文件(我把这个代码了我的计划,我在其中加载CSV的之一)。当我的代码查找一个不存在的文件时,我一直存在的问题之一是Error消息弹出。通过这个循环,这些消息不会出现。如果它将不存在文件的内容分配给mydata.csv,则仅检查mydata.csv是否为列表。如果是,它会继续运行。如果不是,则停止。如果您担心在代码中区分来自不同文件的数据,只需将文件的相关信息插入文件本身的一个常量位置即可。例如,在我的csv中,我的第三列总是包含从其中收集csv其余部分中包含的信息的图像的名称。

希望这可以帮助你一点,即使我看到你已经有一个解决方案:-)。如果你希望你的程序更加自主,这真的只是一个选择。

+1

这是可爱的,我不确定我是否可以使用它与这个特定的程序,但我很高兴看到不同的方式来获取文件。谢谢! – Stephopolis 2012-08-07 14:53:29