我在问你的帮助。我正在努力处理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))