【问题标题】:passing command line arguments to anova将命令行参数传递给 anova
【发布时间】:2019-06-12 01:38:29
【问题描述】:

简单的问题,但我只能找到传递命令行参数的示例使用'file='而不是任何公式。

例如数据.txt

id    var1  group
1     5     1
2     6     1
3     4     1
4     12    2
5     14    2
6     20    2

为什么在命令行中为anova指定组变量不起作用:./anova.R data.txt group

#!/usr/bin/env Rscript

args <- commandArgs(trailingOnly=TRUE)

data1 <- read.table(args[1],sep="\t", header =TRUE)

result <- summary(aov(richness ~ args[2], data=data1))
write("richness",file="alphatests.txt",append=TRUE)
capture.output(result, file="alphatests.txt",append=TRUE)

可变长度不同(为 'args[2]' 找到)调用:摘要 ... -> 评估 -> 评估 -> -> model.frame.default 执行停止

但这确实有效(当两个示例中都有列名“组”时):

#!/usr/bin/env Rscript

args <- commandArgs(trailingOnly=TRUE)

data1 <- read.table(args[1],sep="\t", header =TRUE)

result <- summary(aov(richness ~ group, data=data1))
write("richness",file="alphatests.txt",append=TRUE)
capture.output(result, file="alphatests.txt",append=TRUE)

为什么我不能将命令行参数传递给公式?

【问题讨论】:

  • 你可以试试result &lt;- summary(aov(richness ~ get(args[2]), data=data1))
  • 是的,这行得通。非常感谢!

标签: r anova


【解决方案1】:

我们可以使用标准方法来改变公式

result <- summary(aov(reformulate(args[2], 'richness'), data = data1))

-全码

#!/usr/bin/env Rscript

args <- commandArgs(trailingOnly=TRUE)

data1 <- read.table(args[1], header =TRUE)
result <- summary(aov(reformulate(args[2], 'richness'), data = data1))
print(result)

-在终端中运行脚本

$ Rscript anova.R data.txt group
#            Df Sum Sq Mean Sq F value Pr(>F)  
#group        1 160.17  160.17   17.47 0.0139 *
#Residuals    4  36.67    9.17                 
#---
#Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

注意:假设 data1.txt 中的第二列名称为 'richness'

【讨论】:

    【解决方案2】:

    命令行参数以字符串形式返回,因此当您将其传递给aov 函数时它不起作用。一种解决方法是使用get

    result <- summary(aov(richness ~ get(args[2]), data=data1))
    

    【讨论】:

      猜你喜欢
      • 2015-06-09
      • 2017-10-22
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-13
      相关资源
      最近更新 更多