Home > Enterprise >  manipulate string from command line argument
manipulate string from command line argument

Time:10-17

I'm calling in an argument with optparse, but I'm needing the string of the resulting argument (variable x) to be in the format "test", "test2", "test3" (quotations separated by commas):

# Set up command line arguments 

library("optparse")

option_list = list(
  make_option(c("--test"), type="character", default=NULL, 
              help="test", metavar="character")

opt_parser = OptionParser(option_list=option_list);
opt = parse_args(opt_parser);

# grab argument into x variable

x <- (opt$pathcsv)
print(x)

Entering the command line :

Rscript --vanilla riboeclip_ma.R --pathcsv="test test2 test3"

output is a character type:

"test test2 test3"

However, I would like the format of the x variable to be "test", "test2", "test3"

My code is setup like this (notice how I have "test", "test2", "test3" in a vector):

all_counts.poly.colData <-
   data.frame(Condition =
                c("test", "test2", "test3"))

However, I'd like to pass that x variable instead to achieve the same result (I'm trying to automate this process).

all_counts.poly.colData <-
   data.frame(Condition =
                c(x))

Please let me know if there is a better way to do this, as I'm still new to R and started playing around with the command line arguments yesterday.

CodePudding user response:

Use splitstr from base R to split it into a vector:

strsplit(opt$pathcsv, " ")[[1]]

If you want to add in commas you can use gsub:

gsub(" ", ", ", opt$pathcsv)
[1] "test, test2, test3"

If you want literal quotes use dQuote applied to each and then paste it back together:

paste(sapply(strsplit(opt$pathcsv, " ")[[1]], dQuote), collapse = ",")
[1] "“test”,“test2”,“test3”"

Based on your question you should use strsplit to replicate what you've hardcoded:

data.frame(Condition =
                c("test1", "test2", "test3"))
  Condition
1      test
2     test2
3     test3

x <- strsplit(opt$pathcsv, " ")[[1]]

data.frame(Condition = x)
 Condition
1      test
2     test2
3     test3

c("test", "test1", "test2") is a character vector and you should not try to replicate the syntax of creating a character vector by trying to add in quotes and commas. Instead, parse your command line argument directly into a character vector:

all(strsplit(opt$pathcsv, " ")[[1]] == c("test", "test2", "test3"))
[1] TRUE
  • Related