I have a sparse matrix represented as

```
> (f <- data.frame(row=c(1,2,3,1,2,1,2,3,4,1,1,2),value=1:12))
row value
1 1 1
2 2 2
3 3 3
4 1 4
5 2 5
6 1 6
7 2 7
8 3 8
9 4 9
10 1 10
11 1 11
12 2 12
```

Here the first column is always present (in fact, the first few are present, the rest are not).

I want to get the data into the matrix format:

```
> t(matrix(c(1,2,3,NA,4,5,NA,NA,6,7,8,9,10,NA,NA,NA,11,12,NA,NA),nrow=4,ncol=5))
[,1] [,2] [,3] [,4]
[1,] 1 2 3 NA
[2,] 4 5 NA NA
[3,] 6 7 8 9
[4,] 10 NA NA NA
[5,] 11 12 NA NA
```

Here is what seems to be working:

```
> library(Matrix)
> as.matrix(sparseMatrix(i = cumsum(f[[1]] == 1), j=f[[1]], x=f[[2]]))
[,1] [,2] [,3] [,4]
[1,] 1 2 3 0
[2,] 4 5 0 0
[3,] 6 7 8 9
[4,] 10 0 0 0
[5,] 11 12 0 0
```

Except that I have to replace `0`

with `NA`

myself.

Is there a better solution?

You can do everything with `base`

functions. The trick is to use indexing by a 2-col (row and col indices) matrix:

```
j <- f$row
i <- cumsum(j == 1)
x <- f$value
m <- matrix(NA, max(i), max(j))
m[cbind(i, j)] <- x
m
```

Whether it is better or not than using the `Matrix`

package is subjective. Overkill in my opinion if you are not doing anything else with it. Also if your data had `0`

in the f$value column, they would end up being converted as `NA`

if you are not too careful.

Similar Questions

Basically, I am just trying to do a simple matrix multiplication, specifically, extract each column of it and normalize it by dividing it with its length. #csc sparse matrix self.__WeightMatrix__ = s

How can I convert an ndarray to a matrix in numpy? I'm trying to import data from a csv and turn it into a matrix. from numpy import array, matrix, recfromcsv my_vars = ['docid','coderid','answer1','a

Using the Matrix package I can create a two-dimensional sparse matrix. Can someone suggest a package that would allow me to create a multidimensional (specifically a 3-dimensional) sparse matrix (arra

I am using the cusp library with CUDA to use sparse matrix. Can't I use it in a struct in C like: #include <cusp/coo_matrix.h> #include <cusp/multiply.h> #include <cusp/print.h> #in

So I have this matrix here, and it is of size 13 x 8198. (I have called it 'blah'). This is a sparse matrix, in that, most of its entries are 0. When I do an imagesc(blah), I get the following image:

I would like to use sparse matrices for an analysis. Each cell in the sparse matrix comprises one value from the set {0,1,NA}. NA here represents a missing value. For example, I can use the following

I'm looking for any standard C program that uses OpenMP APIs for a sparse matrix-vector or matrix-matrix multiplications. Can anyone let me know if there are any such programs.

Is there a built-in function in either slam package or Matrix package to convert a sparse matrix in simple triplet matrix form (from slam package) to a sparse matrix in dgTMatrix/dgCMatrix form (from

I have a sparse 988x1 vector (a column in a csr_matrix) created through scipy.sparse. Is there a way to gets its mean and standard deviation without having to convert the sparse matrix to a dense one?

How to get a sparse matrix of size 10M*10M in matlab which is normally distributed random matrix or uniformly distributed random matrix. When I do it below, I got error. n = 10000000; a = sprandn(n,n,

I would appreciate any help, to understand following behavior when slicing a lil_matrix (A) from the scipy.sparse package. Actually, I would like to extract a submatrix based on an arbitrary index lis

Given a large sparse matrix (say 10k+ by 1M+) I need to find a subset, not necessarily continuous, of the rows and columns that form a dense matrix (all non-zero elements). I want this sub matrix to b

How can you take the log base 10 of every element in a sparse matrix (COO)? >>print type(X) <class 'scipy.sparse.coo.coo_matrix'> I've tried this but it doesn't work: import math X.data =

I am trying to compute nearest neighbour clustering on a Scipy sparse matrix returned from scikit-learn's DictVectorizer. However, when I try to compute the distance matrix with scikit-learn I get an

I have an RDD as such: byUserHour: org.apache.spark.rdd.RDD[(String, String, Int)] I would like to create a sparse matrix of the data for calculations like median, mean, etc. The RDD contains the row_

I've been trying to create simple diffuse lighting shader for Android using OpenGL ES 2.0 and getting knowledge from OpenGL 4.0 Shading language cookbook but it doesn't tell much about normal matrix a

I wrote this code to scrape a sparse array from a series of dom elements. when done in one dimension the code works but in 2 dimensions it fails. Is there something i'm missing? 23 function initCellHo

I see 2 implementations of sparse matrix in this package. OpenMapRealMatrix SparseFieldMatrix Both are documented as Sparse matrix implementation based on an open addressed map. Do you know what a

Edit: The huge difference in performance is due to a bug in the test, when set up properly Eigen is 2 to 3 times faster. I noticed that sparse matrix multiplication using C++ Eigen library is much slo

I got a problem when using octave sparse matrix. max(speye(65536)(:)) will result in a 0x0 variable. However, speye(65535) and speye(65537) works. How that happens? My octave version is 3.2.4 in Fedo

I have a binary row vector e.g. b = dec2bin(15) This vector behaves badly when I try to multiply it component-wise with a 'normal' vector. How do I convert b to a normal vector? To be more specific,

I need to overload [] operator in class Sparse Matrix. This operator must work like in 2D table access. For example tab[1][1], return reference. The problem is I have a vector of elements(struct). tem

I have an array of high dimensional however very sparse matrices. I want to normalize them so that column sums of all matrices sum to one. Here is the sample code I use: bg = matrices{1}; for i = 2:le

I have a ticks value of 28000000000 which should be 480 minutes but how can I be sure? How do I convert a ticks value to minutes?

I am using MATLAB to load a text file that I want to make a sparse matrix out of. The columns in the text file refer to the row indices and are double type. I need them to be integers to be able to us

This Creating sparse matrix in MEX has a good example on mxCreateSparse. But this function return a double sparse matrix instead of single. If I want to return a single sparse matrix, what should I do

I have an adjacency weight matrix of a graph. I want to call the bellman ford algorithm of the matlabbgl libaray. How can I convert the matrix to a sparse format?

I want to calculate SVD , but I didn't find good java library for this. Now, I have data store in hashmap, because matrix didn't fit into memory due to the fact that sizes are about 400 000 X 10 000 a

I have a large sparse matrix, and I want to permute its rows or columns to turn the original matrix into a block diagonal matrix. Anyone knows which functions in R or MATLAB can do this? Thanks a lot.

How to convert an Eigen::Matrix<double,Dynamic,Dynamic> to an Eigen::SparseMatrix<double> ? I'm looking for a better way instead of iterate through the dense matrix

I have to implement a sparse matrix (a matrix that has predominantly zeroes, so you only record values different than 0), but I have to implement it using a binary search tree. EDIT: So now I'm thinki

I am trying to do some k-means clustering on a very large matrix. The matrix is approximately 500000 rows x 4000 cols yet very sparse (only a couple of 1 values per row). The whole thing does not f

I want to test some of the newer sparse linear solvers and I want to know if there is a fast way of filling in the matrix. The format I'm interested is CSR (http://goo.gl/hLXYd). Let's say the matrix,

We can construct a sparse matrix from an index and value of non-zero element with the sparseMatrix or spMatrix. Is there any function convert a sparse matrix back to an index and value of all non-zero

I am trying to create a sparse matrix which has a 2D pattern run down the diagonal. This is probably easiest to explain with a quick example. Say my pattern is: [1,0,2,0,1]... I want to create a spars

I'm working on an iPython project with Pandas and Numpy. I'm just learning too so this question is probably pretty basic. Lets say I have two columns of data --------------- | col1 | col2 | ----------

The question is: Is it possible to create a sparse matrix using the following sparse list implementation? In special, using a class template with a class template (SparseList*>)? I've created a cla

Hello I know there are a lot of questions on sparse matrix multiplication, but many of the answers say to just use libraries. I want to do it without using library functions. So far I've done the easy

The dot product of a row and column in a matrix is a 1x1 csr_matrix. How can I efficiently convert that to a scalar? Right now I use sum. M below is a square matrix: dot_product_result = csr_matrix.su

I have a very large Scipy sparse (csr) matrix. I can't use M.toarray() since it triggers ValueError: array is too big. Is there a way of saving a Scipy sparse matrix in Python to be read in Matlab? I

I am working on block compressed sparse row format of sparse matrix. I need to convert a nonzero element into 64 bit floating point. I need a syntax in c OR C++ for that?

I have a scipy.sparse.csr matrix and would like to dump it to a CSV file. Is there a way to preserve the sparsity of the matrix and write it to a CSV?

When I open one file it contains something like this: It's that What is this and how do I convert it to ASCII ?

I'm currently working on a scipy sparse csr matrix. I would like to delete all rows in the matrix that contain 0 in the data array of the matrix (the data array is the 1s and 2s you can see in the exa

I am trying to find the indices of nonzero entries by row in a sparse matrix: scipy.sparse.csc_matrix. So far, I am looping over each row in the matrix, and using numpy.nonzero() to each row to get t

I was wondering if there's any way to have a scipy.sparse.csc_matrix format for mlpy in python. I have worked with mlpy before and have always dealt with non sparse matrices. For instance if I have 5

I recently encountered difficulty when converting a coo_matrix to a dense matrix using scipy. I have a dtype float16 sparse matrix and attempt to convert it to a dense matrix. The error complains abou

I've got a sparse Matrix in R that's apparently too big for me to run as.matrix() on (though it's not super-huge either). The as.matrix() call in question is inside the svd() function, so I'm wonderin

let us consider following matrix A = [ 0 0 0 5 0 2 0 0 1 3 0 0 0 0 4 0] A = 0 0 0 5 0 2 0 0 1 3 0 0 0 0 4 0 if we do sparse(A) ans = (3,1) 1 (2,2) 2 (3,2) 3 (4,3) 4 (1,4) 5 it shows just nonzero el

I Have this code to get shortest path using Dijkstra but I know a real problem involves sparse matrices (matrix populated primarily with zeros). Is there a way to improve efficiency in this code? If