【发布时间】:2016-11-15 04:55:09
【问题描述】:
我一直在尝试运行这个函数,然后弹出“二进制运算符的非数字参数”。我已经看到了很多与我类似的问题,但我仍然无法弄清楚我的代码有什么问题。
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 只是一个任意向量。有更多代码可以模拟步行,但我只是介绍了导致错误的部分。
【问题讨论】:
-
这个:
Itl[j] <- "H"是相当可疑的,如果这个想法是Itl应该保存数字。你知道 R 的强制规则吗?向量只能保存一种数据类型。如果您正在寻找一个不会破坏其他值的“占位符”,不妨试试NA? -
如果您需要
"H"值,您可以在循环中强制返回数字(as.numeric(Itl[j]) + incrm[j]) -
谢谢你和@bradford condon
标签: r binary-operators