将函数从 R 翻译成 rpy2

Translate function from R to rpy2

嗨!我在 R 中使用了一个名为 stylo 的包用于文体学目的(基本上是机器学习,用于根据词汇频率识别文学作者),但我在 Python 中使用它使用 rpy2.

在 R 中,我会执行以下操作:

library(stylo)
cosine.delta = function(x){
        # z-scoring the input matrix of frequencies
        x = scale(x)
        # computing cosine dissimilarity
        y = as.dist( x %*% t(x) / (sqrt(rowSums(x^2) %*% t(rowSums(x^2)))) )
        # then, turning it into cosine similarity
        z = 1 - y
        # getting the results
        return(z)
    }
stylo(distance.measure="cosine.delta")

现在 Python 我知道如何调用 library 和函数 stylo,但我不知道如何定义函数 cosine.delta。任何的想法?我试过这样的事情:

import rpy2.robjects as ro
R = ro.r
R.library("stylo")
cosinedelta = R.function(x){
        # z-scoring the input matrix of frequencies
        x = scale(x)
        # computing cosine dissimilarity
        y = as.dist( x %*% t(x) / (sqrt(rowSums(x^2) %*% t(rowSums(x^2)))) )
        # then, turning it into cosine similarity
        z = 1 - y
        # getting the results
        return(z)
}
R.stylo(distance.measure="cosinedelta")

它说 { 是无效语法。我一直在尝试不同的东西(其他类型的括号,使用

from rpy2.robjects.packages import importr 
base = importr('base')) 

但没有任何效果我对 R 或 rpy2 语法都不太了解...

您可以 运行 通过 rpy2 的任何 R 代码,只需将它放在一个大字符串中,然后将该字符串作为参数传递给 R()。对您来说,以下应该有效:

import rpy2.robjects as ro
R = ro.r
R.library("stylo")
R('''
    cosinedelta <- function(x){
        # z-scoring the input matrix of frequencies
        x = scale(x)
        # computing cosine dissimilarity
        y = as.dist( x %*% t(x) / (sqrt(rowSums(x^2) %*% t(rowSums(x^2)))) )
        # then, turning it into cosine similarity
        z = 1 - y
        # getting the results
        return(z)
    }
    ''')
R('stylo(distance.measure=\"cosinedelta\")')

这基本上只是 R 代码(使用 cosinedelta 而不是 cosine.delta,不确定这是否重要),包裹在 ''' ''' 中使其成为 multi-line python 中的字符串,R( ) 环绕它以将其作为 R 代码执行。

最后一行代码以类似的方式工作。为了安全起见,我在应该直接传递给 R 的引号前面加上了反斜杠,以确保 python 不会尝试对它们做任何有趣的事情,而只是将它们传递给 R。

对于这个答案,我基本上改编了 documentation 中的示例,您自己看一下可能也很有用。