names
R包的bigq
向量的gmp
函数无法正常工作:
> library(gmp)
> x <- as.bigq(c(0.5,0.5))
> names(x) <- c("a", "b")
> names(x)
[1] "a" "b" NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
因此,我为names
类定义了一个bigq
函数,如下所示,它工作正常:
> names.bigq <- function(x) attr(x, "names")[1:length(x)]
> names(x)
[1] "a" "b"
即使names(x) <-
和setNames
也能正常使用names.bigq
功能。但是通过名称访问向量元素不起作用:
> x["a"]
bigq(0)
有没有办法让它发挥作用?如果x["a"]
与x[which(names(x)=="a")]
相同,那么就可以了:
> x[which(names(x)=="a")]
Big Rational ('bigq') :
[1] 1/2
注意:可能的解决方法包括在字符模式下转换和转换x
。
答案 0 :(得分:2)
通过索引提取bigq
向量或矩阵中的元素的函数是内部`[.bigq`
函数:
> gmp:::`[.bigq`
function (x, i = NULL, j = NULL, drop = TRUE)
{
.Call(matrix_get_at_q, x, i, j)
}
<environment: namespace:gmp>
然后用这个覆盖它:
`[.bigq` <- function (x, i = NULL, j = NULL, drop = TRUE)
{
if(is.character(i)){ i <- which(names(x)==i) }
.Call(gmp:::matrix_get_at_q, x, i, j)
}
它有效:
> x <- as.bigq(c(2,5))
> names(x) <- c("a", "b")
> x[1]
Big Rational ('bigq') :
[1] 2
> x["a"]
Big Rational ('bigq') :
[1] 2
<强> 更好: 强>
`[.bigq` <- function (x, i = NULL, j = NULL, drop = TRUE)
{
if(is.character(i)){ i <- sapply(i, function(k) which(names(x)==k), USE.NAMES=FALSE) }
.Call(gmp:::matrix_get_at_q, x, i, j)
}
得到:
> x[c("a","b")]
Big Rational ('bigq') object of length 2:
[1] 1 2
> x[c("b","a")]
Big Rational ('bigq') object of length 2:
[1] 2 1