【问题标题】:R functional programming to read directory and specific number of files with a particular extentionR函数式编程以读取具有特定扩展名的目录和特定数量的文件
【发布时间】:2016-07-24 23:12:41
【问题描述】:

我想在 R 中使用函数和循环执行以下操作:

  1. 从用户输入中读取目录地址(如果输入为空,警告用户提供正确的地址,如果用户选择选项'X',则重复循环并退出)。

  2. 如果目录地址正确(例如 C:/MyDirectory/MySubDirectory),请选择文件夹并检查文件的扩展名。假设该文件夹中有两个“.txt”、一个“.xlsx”和两个“.csv”文件,询问用户从哪个扩展名读取哪些文件?

我尝试了什么:

input <- NULL
while (input != "X" | input != "x" | !is.null(input)){
   input <- readline("Please enter the full path for your files, if you want to exit, enter 'X': ") 
   # Set default directory to the address provided by user
   setwd(input)

   if(input == 'X' | input == 'x'){
      cat("\nYou Chose to exit, Bye!\n")
      exit -1
    }
} 

   FilesListCSV <- list.files(pattern="*.csv", ignore.case=TRUE)
   FilesListXLSX <- list.files(pattern="*.xlsx", ignore.case=TRUE)
   FilesListTXT <- list.files(pattern="*.txt", ignore.case=TRUE)
   cat("There are ", length(FilesListCSV), " CSV file(s), ", length(FilesListXLSX), 
   " Excel File(s), and ", length(FilesListTXT), " Text File(s) in the folder.\n"

   while (opt != "1" | opt != "2" | opt != "3" | !is.null(opt)){
   cat("\nPlease choose extention to read files [1. for CSV, 2. for XLSX, 3. for TXT files.\n")

    opt <- readline("Enter Your Option : ")
   # Example code for reading csv files
   if (opt == "1") {
       library(dplyr)
       library(readr)

       read_file <- list.files(pattern = "*.csv") %>% 
           lapply(read.csv, stringsAsFactors=F) %>% 
           bind_rows 
      }

   }

问题:

  1. 在上面的代码中,While循环抛出以下错误:

    while (input != "X" | input != "x" | !is.null(input)) { : 参数长度为零

  2. 我的代码好像乱七八糟,不知道怎么简单。

有人可以帮帮我吗?

【问题讨论】:

  • @chinsoon12,是的,我也试过了。仍然错误。
  • @chinsoon12 是的!有效。至少对于while循环。

标签: r loops functional-programming


【解决方案1】:

关于你的第一部分,怎么样:

input <- NULL
while(length(input) == 0){
    input <- readline("Please enter the full path for your folder, \nif you want to exit, 
                       enter 'X' (without quote): ") 
    if(input == 'X' | input == 'x'){
       cat("\nYou Chose to exit, Bye!\n")
       return
    } else {

    # Set default directory to the address provided by user
    setwd(input)
    }
 } 

【讨论】:

  • 它运作良好.. 谢谢。我希望得到第二个答案。
猜你喜欢
  • 2021-10-31
  • 2021-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-21
  • 1970-01-01
  • 2010-12-03
  • 2017-05-09
相关资源
最近更新 更多