"二元运算符的非数字参数" R中的错误

时间:2016-07-12 19:35:10

标签: r binary-operators

我一直在试图运行这个函数和"非数字参数到二元运算符"弹出。我已经看到了很多类似于我的问题,但我仍然无法弄清楚我的代码有什么问题。

TakeOneIndStep <- function(Itl, N){     # Itl is a vector  
  foo <- ListMaintenance(Itl, N)        # is a vector of same length as Itl. Displays the coordinates of coalesced walks. 
  incrm <- sample(c(-1, 0, 1), size = length(Itl), replace =  T, prob = c(0.25, 0.5, 0.25))
  for (j in 1:length(Itl)){
    if(Itl[j] %in% foo){
     Itl[j] <- (Itl[j] + incrm[j]) %% N
   }else{
     Itl[j] <- "H"              # H is a "placeholder", just to indicate that that particular chain has coalesced and no longer is updated. 
   }
 }
  return(Itl)
}

错误发生在第六行Itl[j] <- (Itl[j] + incrm[j]) %% N

辅助功能的代码:

ListMaintenance <- function(Temp, N){    # Temp is a vector
  rez <- CheckCoalescence(Temp)
  fubar <- vector()
  for(i in 1:length(rez)){
    for(x in 0:(N-1)){if (x %in% rez[[i]]){fubar[x] <- min(rez[[i]])}
    }
  } 
  return(fubar)                  # output is a vector. Coordinates with the same value have the index of the smallest occurrence.  
}

CheckCoalescence <- function(Pts){
  mar <- unname(split(seq_along(Pts), Pts))
  return(mar)
}

总的来说,我试图模拟一个具有两个以上不同起点的随机游走过程。因此,参数Itl将是每次行走时的值(t-1),并且此函数将递归地更新这些值。

出于实际目的,我尝试使用A <- c(0, 2, 3, 2, 6)TakeOneIndStep(A, N = 9)

测试该功能

在这种情况下,A只是一个任意向量。还有更多代码来模拟漫游,但我刚刚介绍了导致错误的部分。

1 个答案:

答案 0 :(得分:2)

问题是Itl[j] <- "H":您通过向向量添加字符来更改类。链条在您的代码中合并后,Itl[j]对数字操作不再有效。

要解决此问题,我已将其替换为

 Itl[j] <- (Itl[j] + incrm[j]) %% N

  Itl[j] <- (as.numeric(Itl[j]) + incrm[j]) %% N