Я прошу вас помочь. Я боролся с тем, как 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()
. Тем не менее, я получил странную перестановку возврата для 4-го ряда xi_xj
, который содержит (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))