R returns strange order permutation -


i asking helps. struggling way r stores , treats data value. here example:

i have matrix 4x3. on each row, calculate absolute different among each pairs (step 2 in code):

xi_xj[i,1]  = abs(x[i, 1]-x[i, 2]) # different btw 1st , 2nd elements  xi_xj[i,2]  = abs(x[i, 1]-x[i, 3]) # different btw 1st , 3rd elements  xi_xj[i,3]  = abs(x[i, 2]-x[i, 3]) # different btw 2nd , 3rd elements 

once xi_xj computed, order 3 elements on each row in increasing order , return index or permutation (step 3 in code). use function order() this. however, got strange return permutation 4th row of xi_xj containing (0.3, 0.6,0.3). expect return permutation should {1, 3, 2} mean "the first element (0.3) comes first, followed third element (0.3 well), , second comes last (0.6)". when code running, returns me strange order {3,1,2}. confused here. have add #test1 , #test 2 in code, , see xi_xj[4,1] , xi_xj[4,3] "slightly different" amount of 1.110223e-16 weird. suspect due datatype r auto uses treat data, in case "double". don't know how work around this.

here code:

rm(list=ls()) cat("\014") n=4 m = 3  #1. given x matrix n rows , m cols (x=matrix(c(0.1, 0.2, 0.4, 0.1,0.2,0.7, 0.1, 0.4, 0.7, 0.2, 0.4, 0.7), nrow=n, ncol=m))   #2. calculate pairwise distance of each pairs abs(x[k,i]-x[k,j]) in each row kth  (xi_xj <- matrix(0, nrow =n, ncol = m, byrow = true)) (i in 1: n){   xi_xj[i,1]  = abs(x[i, 1]-x[i, 2])   xi_xj[i,2]  = abs(x[i, 1]-x[i, 3])   xi_xj[i,3]  = abs(x[i, 2]-x[i, 3])   }  xi_xj  # 3. in each row, need return permutation value ordered increasingly. #create matrix store permutaion or indexing of increasing order index_xi_xj = matrix(0, nrow=n, ncol=m) (i in 1: n){   #process on each row   (temp <- xi_xj[i,])    #get index of rearangment in increasing order   index_xi_xj[i,]<- order(temp, decreasing= false) } index_xi_xj[4,] # comment on result:  # problem comes 4th row of xi_xj[4, ] containing value {0.3, 0.6, 0.3}.  # once r order them in increasing order, should have correct permutation {1,3,2}  # of ordering instead of {3,1,2} index_xi_xj[4,]   #------------------------------------------- # 4. test 1: check whether data in xi_xj[4,1] == xi_xj[4,1] see on console? xi_xj if(xi_xj[4,1]==xi_xj[4,3]){   cat("equal") }else {print ("different")        cat("error = ", xi_xj[4,1]-xi_xj[4,3]) }  # 5. test 2: however, if order list of c(0.3, 0.6, 0.3), function "order()" returns correct permutation {1, 3, 2} (order(c(0.3, 0.6, 0.3), decreasing=false)) 

i found question setting 'float' storage mode of single precision object. turns out r not support single precision. therefore, values stored 'double' causes strange sort permutation in code.


Comments

Popular posts from this blog

gridview - Yii2 DataPorivider $totalSum for a column -

java - Suppress Jboss version details from HTTP error response -

Sass watch command compiles .scss files before full sftp upload -