在R中存储/制作稀疏向量

时间:2022-06-21 15:42:46

I am generating a sparse vector length >50,000. I am producing it in a for loop. I wonder if there is an efficient way of storing the zeros?

我生成的稀疏矢量长度> 50,000。我在for循环中生成它。我想知道是否有一种存储零的有效方法?

Basically the code looks like

基本上代码看起来像

score = c()
for (i in 1:length(someList)) {
score[i] = getScore(input[i], other_inputs)
if (score[i] == numeric(0))
score[i] = 0    ###I would want to do something about the zeros
}

1 个解决方案

#1


1  

This code will not work. You should preallocate score vector size before looping. Preallocating also will create a vector with zeros. So, no need to assign zeros values, you can only assign numeric results from getScore function.

此代码无效。您应该在循环之前预先分配分数向量大小。预分配还将创建一个带零的向量。因此,无需分配零值,您只能从getScore函数中分配数值结果。

N <- length(someList)  ## create a vector with zeros
score = vector('numeric',N)
for (i in 1:N) {
  ss <- getScore(input[i], other_inputs)
  if (length(ss)!=0)
    score[i] <- ss  
}

#1


1  

This code will not work. You should preallocate score vector size before looping. Preallocating also will create a vector with zeros. So, no need to assign zeros values, you can only assign numeric results from getScore function.

此代码无效。您应该在循环之前预先分配分数向量大小。预分配还将创建一个带零的向量。因此,无需分配零值,您只能从getScore函数中分配数值结果。

N <- length(someList)  ## create a vector with zeros
score = vector('numeric',N)
for (i in 1:N) {
  ss <- getScore(input[i], other_inputs)
  if (length(ss)!=0)
    score[i] <- ss  
}