Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting R command line arguments into integer vectors

Tags:

r

rscript

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?

like image 947
Piyush Shrivastava Avatar asked Mar 22 '16 10:03

Piyush Shrivastava


People also ask

How do you make an integer vector in R?

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.

How do I convert a character vector to a numeric vector in R?

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.

How do you convert a vector to an integer?

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.


1 Answers

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)
like image 170
Jean Lescut Avatar answered Sep 24 '22 02:09

Jean Lescut