问题描述
我正在尝试将一些旧的 Python 代码从 Rpy1 更新到 Rpy2,但有几行代码无法正常运行:
result = rpy.r.kmeans(datnorm,cls,kmeans_iterations,kmeans_nstart)
sse = sum(result['withinss'])
我将 Rpy 依赖项更新为 Rpy2 并重构此代码以使用 Rpy2 importr
加载 R 统计模块和 kmeans
函数。修改后的代码是这样的:
result = rstats.kmeans(matnorm,kmeans_nstart)
sse = sum(result['withinss'])
TypeError: Indices must be integers or slices,not <class 'str'>
我明白这是说我不能使用字符串作为索引,因为 kmeans
正在返回一个整数向量。如果结果不是字典,我如何获得 withinss
值?
解决方法
.rx2()
可能就是您想要的:
result.rx2('withinss')
(见https://rpy2.github.io/doc/v3.4.x/html/vector.html#extracting-r-style)