7

I want to read command line arguments in R through Rscript and use the values stored in them for some integer operations. By default, the command line arguments are imported as characters:

#!/usr/bin/env Rscript
arg <- commandArgs(trailingOnly = TRUE)
x = as.vector(arg[1])
class(x)
x
y = as.vector(arg[2])
class(y)
y
cor.test(x,y)

This is the output of this script:

$ Rscript Correlation.R 3,3,2 4,8,6
[1] "character"
[1] "3,3,2"
[1] "character"
[1] "4,8,6"
Error in cor.test.default(x, y) : 'x' must be a numeric vector
Calls: cor.test -> cor.test.default
Execution halted

How can I convert x and y to numeric vectors?

Piyush Shrivastava
  • 1,046
  • 2
  • 16
  • 43

2 Answers2

7

can you try a strsplit, and as.integer() or as.numeric() ?

#!/usr/bin/env Rscript
arg <- commandArgs(trailingOnly = TRUE)
x = as.integer(strsplit(arg[1], ",")[[1]])
class(x)
x
y = as.integer(strsplit(arg[2], ",")[[1]])
class(y)
y
cor.test(x,y)
Jean Lescut
  • 1,387
  • 1
  • 12
  • 17
3

Given x <- "3,3,2"

You can obviously split the character on the , criterion and cast it to numeric.

as.numeric(strsplit(x,",")[[1]])

Another approach would be to evaluate this string expression as if it was part of an instruction. I wouldn't call this solution more clever in this situation, but it is still worth mentioning.

eval(parse(text=paste("c(",x,")",sep="")))
Vongo
  • 1,325
  • 1
  • 17
  • 27