Running R script in RStudio with arguments

I am trying to run an R script in RStudio that takes three arguments. How do I structure the source command?

When i run source("countSteps.R argument1 argument2 argument3") I receive an error

Sorry I know this is a basic syntax question but i have several iterations and I am stuck

What do you mean by 'it takes arguments'?
is there some part of the script that you can reproduce here, that indicates that?

I mean that I want to pass 3 arguments while running the script using the source command

args = commandArgs(trailingOnly=TRUE)
library(phangorn)
print(length(args))
if (length(args) < 3) {
stop(" Usage: countSteps.R <alignment.fasta> <tree.nex> <output.txt>", call.=FALSE)
}

I would edit that code to only assign commandArgs to args if its populated. Therefore a calling script could already have assigned args before sourcing the script that would make use of those

Sorry I'm not sure what you mean. Are you saying I should define the arguments before running the script?

Could you show me what that might look like?

withargs.R

if (length(commandArgs(trailingOnly=TRUE))>0) {
  args <- commandArgs(trailingOnly=TRUE)
}
# library(phangorn)
print(length(args))
if (length(args) < 3) {
  stop(" Usage: countSteps.R <alignment.fasta> <tree.nex> <output.txt>", call.=FALSE)
}

cat("You ran the program with ", args,"\n")

new_value <- paste0(args)

using withargs.R

args <- c("a1","b2","c3")
source("withargs.R")
new_value

Thanks! This was very helpful

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.