【发布时间】:2016-07-24 23:12:41
【问题描述】:
我想在 R 中使用函数和循环执行以下操作:
从用户输入中读取目录地址(如果输入为空,警告用户提供正确的地址,如果用户选择选项'X',则重复循环并退出)。
如果目录地址正确(例如 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
}
}
问题:
-
在上面的代码中,While循环抛出以下错误:
while (input != "X" | input != "x" | !is.null(input)) { : 参数长度为零
我的代码好像乱七八糟,不知道怎么简单。
有人可以帮帮我吗?
【问题讨论】:
-
@chinsoon12,是的,我也试过了。仍然错误。
-
@chinsoon12 是的!有效。至少对于while循环。
标签: r loops functional-programming