I've written an R script in RStudio for purposes of computing transfer entropy between two vectors, x and y, and wish to call it from Python and verify that the results are consistent to see if I'm doing things right:
In RStudio:
TE <- function(x,y) {
library(RTransferEntropy)
library(future)
plan(multiprocess)
set.seed(12345)
shannon_te <-transfer_entropy(x,y,nboot=1000)
result=shannon_te
return(result)
}
The script compiles without error. Now I test it:
n <- 2500
x <- rep(0, n + 200)
y <- rep(0, n + 200)
x[1] <- rnorm(1, 0, 1)
y[1] <- rnorm(1, 0, 1)
for (i in 2:(n + 200)) {
x[i] <- 0.2 * x[i - 1] + rnorm(1, .2, 1)
y[i] <- sqrt(abs(x[i - 1])) + rnorm(1, .2, 1)
}
x <- x[-(1:200)]
y <- y[-(1:200)]
TE(x,y) works fine and produces transfer entropy values and their corresponding p-values, which show x has a causal effect on y, but not vice versa.
Now I wish to call this script from within Python using a function named T:
import numpy as np
from rpy2.robjects.packages import importr
import rpy2.robjects as ro
importr('RTransferEntropy',lib_loc='/Library/Frameworks/R.framework/
Versions/3.6/Resources/library')
base = importr('base')
utils = importr('utils')
import rpy2.robjects.packages as rpackages
import rpy2.robjects
def T(x,y):
r=ro.r
r.source("TE.R")
t=r.TE(x,y)
return t
None of this yields any errors. I want to test this by defining the same vectors, x and y, in Python and call the Python function above to verify that x has a causal influence on y but not vice versa:
time=np.arange(10)
for t in time:
x[t+1]=.2*x[t]+np.random.normal(1,.2,1)
y[t+1]=ma.sqrt(abs(x[t]))+np.random.normal(1,.2,1)
T(x,y)
This produces the error message below: