Convert numpy array to rpy2 matrix, Kmeans

I have a numpy 2D self.sub array and I want to use it in rpy2 kmeans. k = robjects.r.kmeans (self.sub, 2,20) I always get the following error: valueError: nothing can be done for the type at the moment! What can I do?

+2
source share
1 answer

From rpy2 docs , R-matrices are just vectors with their set of dim attributes. So, for a two-dimensional two-dimensional array x

import rpy2.robjects as robj

nr, nc = x.shape
xvec = robj.FloatVector(x.transpose().reshape((x.size))
xr = robj.r.matrix(xvec, nrow=nr, ncol=nc)

You need to transpose the numpy array, because R fills the matrices in columns.

Edit: Actually, you could just set byrow = True in the matrix function R, and then you would not need to transpose.

+4
source

All Articles