R: Difficulties manipulating bigz vectors/list

泄露秘密 提交于 2019-12-13 07:27:29

问题


Below are two schemes that I use on a daily basis that I'm having trouble with using the gmp package:

Normal Behavior:

### example 1 (changing a subset of a vector)
> v1 <- rep(1,10)
> v1[3:7] <- 2:6
> v1
 [1] 1 1 2 3 4 5 6 1 1 1

### example 2 (flattening a list to a vector)
> mylist1 <- list(1:5,6:10)
> unlist(mylist1)
 [1]  1  2  3  4  5  6  7  8  9 10

GMP equivalents:

### example 1 (when changing a subset, the vector is lost)
> v2 <- as.bigz(rep(1,10))
> v2[3:7] <- as.bigz(2:6)
> v2
Big Integer ('bigz') 10 x 1 matrix:
  [,1]
 [1,] 1   
 [2,] 1   
 [3,] 2   
 [4,] 3   
 [5,] 4   
 [6,] 5   
 [7,] 6   
 [8,] 1   
 [9,] 1   
[10,] 1

### example 2 (strange behavior when flattening)
> mylist2 <- list(as.bigz(1:5),as.bigz(6:10))
> unlist(mylist2)
[1] 05 00 00 00 01 .... ##### many more "raw"-like entries

It would be nice if there were gmp equivalents (i.e. unlist.bigz) as we know that objects that "grow" in R can be excessively slow. Most of the time, I'm forced to declare an empty bigz vector and constantly add to it like:

> v3 <- as.bigz(rep(1,2))
> v3 <- c(v3, as.bigz(2:6))
> v3 <- c(v3, as.bigz(rep(1,3)))
> v3
Big Integer ('bigz') object of length 10:
    [1] 1 1 2 3 4 5 6 1 1 1
>  

I typically declare vectors with a given mode and length, but when I try to do this with a bigz vector like: v4 <- as.bigz(vector(length=n)) and then try to populate subsets of the vector, I get results like the above (i.e. a matrix with one column). This is highly undesirable.


回答1:


You can use the c function to combine a list of bigz objects:

bigz.list <- list(
  as.bigz(1),
  as.bigz(1),
  as.bigz(2:6),
  as.bigz(rep(1,3)))

> do.call(c, bigz.list)
Big Integer ('bigz') object of length 10:
 [1] 1 1 2 3 4 5 6 1 1 1


来源:https://stackoverflow.com/questions/34926000/r-difficulties-manipulating-bigz-vectors-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!