簡體   English   中英

R中的“二進制運算符的非數字參數”錯誤

[英]“non-numeric argument to binary operator” error in R

我一直在嘗試運行此功能,然后彈出“二進制運算符的非數字參數”。 我已經看到很多類似我的問題,但是我仍然無法弄清楚我的代碼有什么問題。

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 <- c(0, 2, 3, 2, 6)TakeOneIndStep(A, N = 9)測試該函數

在這種情況下, A只是一個任意向量。 還有更多代碼可以模擬行走,但是我只介紹了導致錯誤的部分。

問題是Itl[j] <- "H" :您通過向向量添加字符來更改類。 一旦鏈在您的代碼中合並, Itl[j]就不再對數字運算有效。

為了解決這個問題,我更換了

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM