此函数应采用用户在第一个readline()
提示符中输入的整数,然后根据该整数运行readline()
输入的下一部分。
如果numSampFolders
== 1,则根据下面的代码,它只需要一个示例文件夹名称。同样,如果numSampFolders
== 2,那么它需要两个示例文件夹名称。
必须有一个更好的方式来写这个,而不是我如何设置它(并且我真的不想最终得到几十个if()
语句只是为了涵盖每一个可能性...... )。例如,如果numSampFolders = 24,则代码应通过readline()
要求用户输入24个名称并将这些名称存储为全局变量。 (我知道使用list.files()
可以更轻松地完成此操作,但是同一目录中的文件夹不是必需的。)
谢谢您的想法。
set_params <- function(){
numSampFolders <- (readline("How many sample folders are you using? "))
numSampFolders <<- as.numeric(numSampFolders)
if (numSampFolders == 1)
SampFolder1 <<- readline("Enter the name of your only sample folder: ")
if (numSampFolders == 2)
SampFolder1 <<- readline("Enter the name of sample folder 1: ")
SampFolder2 <<- readline("Enter the name of sample folder 2: ")
}
if(interactive()) set_params()
答案 0 :(得分:1)
一般方法是使用lapply
(或sapply/for
)进行迭代,使用R动词assign
。 assign
的行为与<-
相似,让assign
行为与<<-
相似的技巧是指定envir = .GlobalEnv
的环境。请参阅以下解决方案
set_params <- function(){
numSampFolders <- (readline("How many sample folders are you using? "))
numSampFolders <<- as.numeric(numSampFolders)
if (numSampFolders == 1) {
SampFolder1 <<- readline("Enter the name of your only sample folder: ")
} else if (numSampFolders > 1) {
lapply(seq_len(numSampFolders), function(i) assign(paste0("SampFolder", i), readline(paste0("Enter the name of sample folder ", i, ": ")), envir = .GlobalEnv))
}
}
if(interactive()) set_params()
这是我的控制台的输出
ls()
# character(0)
# How many sample folders are you using? 2
# Enter the name of sample folder 1: ok
# Enter the name of sample folder 2: whatever
# [[1]]
# [1] "ok"
# [[2]]
# [1] "whatever"
ls()
# [1] "numSampFolders" "SampFolder1" "SampFolder2" "set_params"
SampFolder1
# [1] "ok"
您可能不希望lapply
将值打印到控制台(在这种情况下,这是副作用)。以下是我所指的
# [[1]]
# [1] "ok"
在这种情况下,您可以使用purrr::walk
循环而不会产生副作用。
library(purrr)
set_params <- function(){
numSampFolders <- (readline("How many sample folders are you using? "))
numSampFolders <<- as.numeric(numSampFolders)
if (numSampFolders == 1) {
SampFolder1 <<- readline("Enter the name of your only sample folder: ")
} else if (numSampFolders > 1) {
walk(seq_len(numSampFolders), function(i) assign(paste0("SampFolder", i), readline(paste0("Enter the name of sample folder ", i, ": ")), envir = .GlobalEnv))
}
}
if(interactive()) set_params()