names
R包的bigq
vector 的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
函数正常工作。但是按其名称访问 vector 元素不起作用:> x["a"]
bigq(0)
有办法使它起作用吗?如果
x["a"]
与x[which(names(x)=="a")]
相同,则可以:> x[which(names(x)=="a")]
Big Rational ('bigq') :
[1] 1/2
注意:可能的解决方法是在字符模式下转换和反向转换
x
。 最佳答案
通过其索引从bigq
vector 或矩阵中提取元素的函数是内部`[.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