【问题标题】:Passing code parameters through a file "parameters.txt"通过文件“parameters.txt”传递代码参数
【发布时间】:2016-05-09 13:24:02
【问题描述】:

我想让其他用户轻松使用我的代码。为此,我想提供一个文件“parameters.txt”,用户可以在其中轻松更改值。我还想在其中插入 cmets(以使其更清晰)。它必须是这样的:

# File of parameters
#
# Here put the year you want to analyze.
# You can choose:
# 1) 2000
# 2) 2001
# 3) 2002
# 4) 2003
year    2004
# Here put the team you want to analyze
# Choose it between 
# 1) "Lazio"
# 2) "Juventus"
# 3) "Inter"
team    Lazio

当我阅读文件时,我不想发表评论。换句话说,我想阅读除以“#”开头的所有行。

  1. 这是传递参数的好方法吗?
  2. 你知道我怎样才能只取我感兴趣的线路吗?

【问题讨论】:

  • 你可以做类似xx <- readLines("/tmp/tmpfile.txt"); xx[!grepl("^#", xx)]的事情。至于这是否是一个好方法,可能更常见的是使用 YAML 之类的标记语言来处理这类事情。但是,如果您可以确保参数文件总是像上面那样格式正确,那么您自己解析我们的参数应该不难。
  • read.table 会很好地读取这个文件。默认情况下,它会跳过以 # 开头的行

标签: r input parameter-passing


【解决方案1】:

按照 MrFlick 的建议,我找到了read.table 的解决方案:

parameters <- read.table("./parametri.txt",                                           
                          header = FALSE, blank.lines.skip = TRUE, comment.char="#",   
                          skip = 12     , skipNul = TRUE         , fill=TRUE)

假设参数文件在当前文件夹中。

【讨论】:

    猜你喜欢
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2011-12-25
    相关资源
    最近更新 更多