2016-03-22 18 views
3

RからRscriptのコマンドライン引数を読み込み、いくつかの整数演算にそれらの値を使用します。デフォルトでは、コマンドライン引数は、文字としてインポートされます。Rのコマンドライン引数を整数ベクトルに変換する

#!/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) 

これは、このスクリプトの出力です:

$ 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 

にはどうすれば数値ベクトルにxとyを変換することができますか?

答えて

4

あなたはstrsplitとas.integer()またはas.numeric()を試すことができますか? x <- "3,3,2"

考える

#!/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) 
2

あなたは明らか,基準に文字を分割し、numericにキャストすることができます。

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

もう1つの方法は、この文字列式をあたかも命令の一部であるかのように評価することです。このような状況では、私はこのソリューションをもっと巧妙に呼ぶつもりはありませんが、言及する価値はまだあります。

eval(parse(text=paste("c(",x,")",sep=""))) 
関連する問題