[英]Translate function from R to rpy2
嗨! 我在 R 中使用了一個名為stylo
的包用於文體測量(基本上是機器學習,用於根據詞匯頻率識別文學作者),但我在 Python 中使用rpy2
使用它。
在 RI 中將執行以下操作:
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
,不確定這是否重要),包裹在''' '''
以使其成為python中的多行字符串,並且R( )
包裹在它周圍將其作為 R 代碼執行。
最后一行代碼的工作方式類似。 為安全起見,我將反斜杠放在應該直接傳遞給 R 的引號前面,以確保 python 不會嘗試對它們做任何有趣的事情,而只是將它們傳遞到 R 中。
對於這個答案,我基本上改編了文檔中的一個示例,您自己查看它可能也很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.