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?
To create an integer vector, we can use c() function. A number by default is considered double in R. If the number is followed by the character L , then it is an integer. In the following example, we create an integer vector with length 5.
To convert a character vector to a numeric vector, use as. numeric(). It is important to do this before using the vector in any statistical functions, since the default behavior in R is to convert character vectors to factors.
To convert a given character vector into integer vector in R, call as. integer() function and pass the character vector as argument to this function. as. integer() returns a new vector with the character values transformed into integer values.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With