R csv(或txt)格式的配置文件
我想创建一个配置文件。在R文件中,它将如下所示:R csv(或txt)格式的配置文件,r,R,我想创建一个配置文件。在R文件中,它将如下所示: #file:config.R min_birthday_year <- 1920 max_birthday <- Sys.Date() %m+% months(9) min_startdate_year <- 2010 max_startdate_year <- 2022 #文件:config.R 我建议的第一件事是查看包装。 它允许您在yaml文本文件中指定变量。我没有用过它,但它看起来很整洁,看起来可能是一个很好的解
#file:config.R
min_birthday_year <- 1920
max_birthday <- Sys.Date() %m+% months(9)
min_startdate_year <- 2010
max_startdate_year <- 2022
#文件:config.R
我建议的第一件事是查看包装。
它允许您在yaml文本文件中指定变量。我没有用过它,但它看起来很整洁,看起来可能是一个很好的解决方案
如果您不想使用它,那么如果您的csv是这样的,一列中有var名称,下一列中有值:
min_birthday_year,1920
max_birthday,Sys.Date() %m+% months(9)
min_startdate_year,2010
max_startdate_year,2022
然后你可以这样做:
# Read in the file
# assuming that names are in one column and values in another
# will create vars using vals from second col with names from first
config <- read.table("config.csv", sep = ",")
# mapply with assign, with var names in one vector and values in the other
# eval(parse()) call to evaluate value as an expression - needed to evaluate the Sys.Date() thing.
# tryCatch in case you add a string value to the csv at some point, which will throw an error in the `eval` call
mapply(
function(x, y) {
z <- tryCatch(
eval(parse(text = y)),
error = function(e) y
)
assign(x, z, inherits = TRUE)
},
config[[1]],
config[[2]]
)
#在文件中读取
#假设名称在一列中,值在另一列中
#将使用第二列的VAL和第一列的名称创建VAR
我想知道:到底为什么?更改csv文件难道不像更改R文件那样麻烦吗?用另一种方式思考只会让阅读变得更困难。我知道,但告诉我的经理,把他的e-mailaddresssadistic@jackass.comhey,这是我的电子邮件地址!;)但说真的,你(或者他)会如何将CSV或TXT格式化?如果他想要不同的东西,他应该有一个适当的需求描述。