2015-07-10 103 views
-1

問題:比較陣列以標量

lessthanorequalto操作比較的二維陣列和一個標量變量,都與數值與(< =)和陣列中分配所有這些值到一個矢量。

我想在R加速此任務。

現在,下面是我使用的代碼(這顯然是相當費時)

代碼我現在使用:

2d_examplearray; #我的2維數組實際大小3500 X 4200 my_scalarvariable = 5; #一些任意值,因爲這是一個例子

dims_2darray = dim(2d_examplearray); #不要。行&列的信息

# First create and then initialize vectors for storing values accordingly as specified in if # condition below 

eachelementin_ltvector<-vector(); 
eachelementin_gtvector<-vector(); 

eachelementin_ltvector=1; 
eachelementin_gtvector=1; 

for (eachrow in 1 : dims_2darray[1]) 
{ 
for (eachcol in 1 : dims_2darray[2]) 
{ 
if(2d_examplearray[eachrow,eachcol]<my_scalarvariable) 
{ 
vector_lessthanvalue[eachelementin_ltvector]=2d_examplearray[eachrow,eachcol]; 
eachelementin_ltvector=eachelementin_ltvector+1; 
} 
else # greater than or equal to my scalar variable then 
{ 
vector_greaterthanvalue[eachelementin_gtvector]=2d_examplearray[eachrow,eachcol]; 
eachelementin_gtvector=eachelementin_gtvector+1; 
} 
} 
} 

感謝就同樣的問題在我以前的帖子的輸入。 我是新來的R和這個Q &論壇。

再次感謝

+3

請出示基於這樣一個小例子,預期的輸出。有關指南,請查看[here](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – akrun

+1

您是否嘗試過谷歌R子集? – nicola

+1

'indx < - yourmatrix <= scalarvariable; yourmatrix [indx] < - vector1'但是,vector1的長度應該與'yourmatrix'的長度相同。沒有一個可重複的例子,代碼不容易 – akrun

回答

0

您需要提供一個reproducible example,但您的解決方案可能會是這樣的形式

m= 3 # 3500 
n= 4 # 4200 
set.seed(123) 
m <- matrix(rnorm(m*n), m, n) 
m 
#   [,1]  [,2]  [,3]  [,4] 
# [1,] -0.5604756 0.07050839 0.4609162 -0.4456620 
# [2,] -0.2301775 0.12928774 -1.2650612 1.2240818 
# [3,] 1.5587083 1.71506499 -0.6868529 0.3598138 

v = 1.5 # the value you want elements less than or equal to 

m <= v 
#  [,1] [,2] [,3] [,4] 
# [1,] TRUE TRUE TRUE TRUE 
# [2,] TRUE TRUE TRUE TRUE 
# [3,] FALSE FALSE TRUE TRUE 

,但你需要指定要如何矩陣從二對一映射尺寸。

例如,你可以做

unlist(m[m <= v]) 

正如你可以看到那張從上到下,從左到右。

# [1] -0.56047565 -0.23017749 0.07050839 0.12928774 0.46091621 -1.26506123 -0.68685285 -0.44566197 1.22408180 0.35981383 
+0

我開始做這個評論,但我需要一個代碼塊。 – C8H10N4O2

0

從你的問題,我不能說,如果這就是你在尋找什麼,但我創造了可能會有所幫助的例子:

mat <- matrix(1:14700000, 3500, 4200) 

vector <- c(-1:-1000000) 
scalar <- 1000000 
mat[mat <= scalar] <- c(-1:-1000000) 

注意vector必須是相同的長度元素被替換。

+0

謝謝大家的時間和投入。我是R編程和這個論壇的新手。 – user2701513

0

「這」可能是有用的:

> A <- matrix(sample(3500*4200)/(3500*4200),3500,4200) 

> b <- 0.3 

> v <- A[which(A<=b)] 

> system.time(for (n in 1:100) { A[which(A<=b)] }) 
     User  System verstrichen 
     30.61  6.05  37.78 

> summary(v) 
    Min. 1st Qu. Median  Mean 3rd Qu.  Max. 
7.00e-08 7.50e-02 1.50e-01 1.50e-01 2.25e-01 3.00e-01 

> w <- unlist(A[A<=b]) 

> system.time(for (n in 1:100) { unlist(A[A<=b]) }) 
     User  System verstrichen 
     32.51  7.22  40.14 

> summary(w) 
    Min. 1st Qu. Median  Mean 3rd Qu.  Max. 
7.00e-08 7.50e-02 1.50e-01 1.50e-01 2.25e-01 3.00e-01 

> identical (v,w) 
[1] TRUE