比较两个向量时运行相同功能时出错

时间:2019-04-13 19:09:15

标签: r rstudio

我有一个向量(长度为8),每次for循环运行时,在向量中随机更改一个元素。我想用一个固定的向量(Destination)检查新生成的向量,并将有效情况保存在计数变量(Time_to_Destination)中。但是,当我使用same()函数时,Time_to_Destination中没有保存的记录。我的代码有什么问题吗?

我尝试了same(),all.equal() 如果我注释掉if(identical()),则计算变量Time_to_Destination

rm(list = ls())

library(igraph)
#Plot the graph
graph_MC <- graph(edge = c(1,2,1,3,2,3,2,4,3,4), n = 4, directed = F)

plot(graph_MC)
#Initial position
X_0 <- c(1,2,3,1)

Destination <- c(3,1,2,3)

X <- X_0

Time_to_destination <- 0
#I would like to see how many time I arrive to the Destination, which have a valid set of color
for(i in 1:10000){
  #Generate a random node
  a <- as.integer(runif(1,1,4))
  #Generate a random color of the node
  q <- as.integer(runif(1,1,3))

  test_vector <- X

  test_vector[a] = q
  #Check if the new set of color is valid
  if (a == 1) {
    if ((q != test_vector[2]) & (q != test_vector[3])) {
      X = test_vector 
      if (identical(X, Destination)){
        Time_to_destination = Time_to_destination + 1
      }
    }
  }

  if (a == 2) {
    if ((q != test_vector[1]) & (q != test_vector[3]) & (q != test_vector[4])) {
      X = test_vector
      if (identical(X, Destination)){
        Time_to_destination = Time_to_destination + 1
      }
    }
  }


  if (a == 3) {
    if ((q != test_vector[1]) & (q != test_vector[2]) & (q != test_vector[4])) {
      X = test_vector 
      if (identical(X, Destination)){
        Time_to_destination = Time_to_destination + 1
      }
    }
  }


  if (a == 4) {
    if ((q != test_vector[3]) & (q != test_vector[2])) {
      X = test_vector 
      if (identical(X, Destination)){
        Time_to_destination = Time_to_destination + 1
      }
    }
  }
}
Time_to_destination

0 个答案:

没有答案