我在問你的幫助。我正在努力處理R存儲和處理數據價值的方式。這裏是我的例子:R返回奇怪的順序排列
我有一個矩陣4x3。在每一行上,我計算每對(步驟2在我的代碼)之間的絕對不同:
xi_xj[i,1] = abs(x[i, 1]-x[i, 2]) # the different btw the 1st and 2nd elements
xi_xj[i,2] = abs(x[i, 1]-x[i, 3]) # the different btw the 1st and 3rd elements
xi_xj[i,3] = abs(x[i, 2]-x[i, 3]) # the different btw the 2nd and 3rd elements
一旦xi_xj
被計算,我會爲了在每行3個元素以遞增順序並返回索引或排列(我的代碼中的第3步)。我使用功能order()
來執行此操作。但是,我對xi_xj
的第4行有奇怪的返回排列,其中包含(0.3, 0.6,0.3)
。我預計返回排列應該是{1, 3, 2}
這意味着「第一個元素(0.3)
第一個,第三個元素(0.3),第二個最後(0.6)」。當代碼運行時,它會返回奇怪的順序{3,1,2}。我在這裏很困惑。我在我的代碼中添加了#test1
和#test 2
,我清楚地看到xi_xj[4,1]
和xi_xj[4,3]
「略有不同」,數量爲1.110223e-16
,這很奇怪。我懷疑這是由於R auto用來處理我的數據的數據類型,在這種情況下它是「雙倍」的。我不知道如何解決這個問題。
這裏是我的代碼:
rm(list=ls())
cat("\014")
N=4
M = 3
#1. given X matrix N rows and 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 the 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))
for (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, we will need to return the permutation which their value are ordered increasingly.
#create a matrix to store the permutaion or indexing of the increasing order
index_xi_xj = matrix(0, nrow=N, ncol=M)
for (i in 1: N){
#process on each row
(temp <- xi_xj[i,])
#get the index of rearangment in increasing order
index_xi_xj[i,]<- order(temp, decreasing= FALSE)
}
index_xi_xj[4,]
# COMMENT ON THE RESULT:
# PROBLEM comes from the 4th row of the xi_xj[4, ] containing value {0.3, 0.6, 0.3}.
# Once R order them in increasing order, we should have CORRECT permutation {1,3,2}
# of their ordering instead of {3,1,2} as index_xi_xj[4,]
#-------------------------------------------
# 4. test 1: check whether the data in xi_xj[4,1] == xi_xj[4,1] as we see on the 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 we order the list of c(0.3, 0.6, 0.3), the function "order()" returns correct permutation {1, 3, 2}
(order(c(0.3, 0.6, 0.3), decreasing=FALSE))