将 numpy 数组转换为 Matrix rpy2, Kmeans [英] convert numpy array to Matrix rpy2, Kmeans
问题描述
我有一个 numpy 二维数组 self.sub我想在 rpy2 kmeans 中使用它.k = robjects.r.kmeans(self.sub,2,20)我总是收到以下错误:valueError: 目前对该类型无能为力!我能做什么?
I have a numpy 2D array self.sub 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?
推荐答案
来自 rpy2 docs,R 矩阵只是带有暗属性集的向量.所以对于一个 numpy 二维数组 x
From the rpy2 docs, R matrices are just vectors with their dim attribute set. So for a numpy 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)
您必须转置 numpy 数组,因为 R 按列填充矩阵.
You have to transpose the numpy array because R fills matrices by columns.
实际上,您可以在 R 矩阵函数中设置 byrow=True,然后您就不需要转置了.
Actually, you could just set byrow=True in the R matrix function, and then you wouldn't need to transpose.
这篇关于将 numpy 数组转换为 Matrix rpy2, Kmeans的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!