0

我有一个代表对象状态的数字,我想检查其中一个状态。例如,如果数字是“22”,它应该在检查 16、4 或 2 时返回 true,而对于其他任何值都返回 false。我的功能是

containsOrderType <- function(orderType, state) #returns whether the bitmask translates to containing that order type
{
  state <- as.numeric(state)
  if(orderType>state) return(FALSE)
  binState <- as.integer(state)
  class(binState) <- "binmode"
  binState <- as.character(binState)
  dim(binState) <- dim(state)
  X<-log2(orderType)+1
  if(str_sub(binState,-X,-X)==1) return(TRUE)
  return(FALSE)
}

直到今天这一个月都运行良好,我很确定问题在于 dim(state) 正在采用 dim([an integer]) 似乎总是“NULL”。这发生在 R 2.15.3 和 R 3.0.1 中。如果那是一致的,我会得到它,但是这个功能在一段时间内完全按照预期工作,现在它没有。这是 R.Utils 中的 intToBin 函数,它与我的函数的第 3-6 行相同。

function (x) 
{
    y <- as.integer(x)
    class(y) <- "binmode"
    y <- as.character(y)
    dim(y) <- dim(x)
    y
}

>dim
function (x)  .Primitive("dim")
> class
function (x)  .Primitive("class")

所以那些还没有被包或类似的奇怪东西覆盖。

4

3 回答 3

5

试试bitwAndbase R中的函数,例如

> bitwAnd(22, 2^(0:10))
 [1]  0  2  4  0 16  0  0  0  0  0  0
> bitwAnd(1:22, 16)
 [1]  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0 16 16 16 16 16 16 16
> bitwAnd(4, 2060)
[1] 4
> (bitwAnd(8, 2060) != 0) == containsOrderType(8, 2060)
> TRUE

bitAndbitops包中。

于 2013-09-27T00:24:13.420 回答
0

显然我在我的程序中移动了一些东西,并且不知何故没有包含 R.utils 本身......很奇怪,因为我认为我复制了代码,所以我必须包含那个包。无论如何,我会留下这个以防其他人需要它。由于无论如何我都包含该软件包,因此我的代码可以简化为:

containsOrderType <- function(orderType, state) #returns whether the bitmask translates to containing that order type
{
  state <- as.numeric(state)
  if(orderType>state) return(FALSE)
  binState <- intToBin(as.integer(state))
  X<-log2(orderType)+1
  if(str_sub(binState,-X,-X)==1) return(TRUE)
  return(FALSE)
}
于 2013-09-26T22:06:16.843 回答
0

您可以gmp::factorize用作:

Rgames> 2%in%as.numeric(factorize(20))
[1] TRUE

请注意gmp函数返回bigz类的东西,这就是为什么

Rgames> 2%in%factorize(20)
[1] FALSE

发生。

回答hedgeandlevered的评论——如果你想要2你的号码的最大功率,那么

Rgames> 2^(sum(factorize(20)==2))
[1] 4

会为你做的。(另请注意,==此处将其参数强制为一个公共类)

于 2013-09-27T11:44:26.693 回答