Home > Software engineering >  Add commas between character
Add commas between character

Time:10-17

I'm calling in an argument with optparse, but I'm needing the format of the resulting argument (variable x) to be what is listed below:

# 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"

How can I get the output of x variable to be "test", "test2", "test3" without affecting how the command line argument is given.

CodePudding user response:

You may split the x value on whitespace and unlist to get a vector of string.

x <- (opt$pathcsv)
#x <- "test test2 test3"
x1 <- unlist(strsplit(x, '\\s '))
x2 <- paste0(sprintf('"%s"', x1), collapse = ',')
x2
#[1] "\"test\",\"test2\",\"test3\""

While displaying R escapes quotes, the real string can be viewed by cat.

cat(x2)
#"test","test2","test3"

CodePudding user response:

We can also do

toString(dQuote(strsplit(x, "\\s ")[[1]], FALSE))
[1] "\"test\", \"test2\", \"test3\""

data

x <- (opt$pathcsv)
x <- "test test2 test3"
  •  Tags:  
  • r
  • Related