简体   繁体   中英

passing command line arguments to anova

Simple problem, but only examples I can find of passing command line arguments use 'file=' and not any formulas.

eg data.txt

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

Why doesn't this work to specify the group variable to anova in the command line: ./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)

variable lengths differ (found for 'args[2]') Calls: summary ... -> eval -> eval -> -> model.frame.default Execution halted

But this does work (when there is a column name 'group' in both examples):

#!/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)

Why can't I pass a command line argument to a formula?

We can use standard methods for changing the formula

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

-fullcode

#!/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)

-run the script in terminal

$ 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

NOTE: Assuming the second column name to be 'richness' in data1.txt

Command-line arguments are returned as strings so it does not work when you pass it to aov function. One workaround is to use get

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM