The names
function for bigq
vectors of the gmp
R package does not work as one could expect:
> 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
Thus I define a names
function for the bigq
class as follows, and it works fine:
> names.bigq <- function(x) attr(x, "names")[1:length(x)]
> names(x)
[1] "a" "b"
Even names(x) <-
and setNames
work fine with the names.bigq
function. But the access to an element of a vector by its name does not work:
> x["a"]
bigq(0)
Is there a way to make it work ? If x["a"]
were the same as x[which(names(x)=="a")]
then it would be fine:
> x[which(names(x)=="a")]
Big Rational ('bigq') :
[1] 1/2
Note: A possible workaround consists in converting and back-converting x
in character mode.
The function extracting an element in a bigq
vector or matrix by its index is the internal `[.bigq`
function:
> gmp:::`[.bigq`
function (x, i = NULL, j = NULL, drop = TRUE)
{
.Call(matrix_get_at_q, x, i, j)
}
<environment: namespace:gmp>
Then overwrite it by this one:
`[.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)
}
And it works:
> 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
Better:
`[.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)
}
to get:
> 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