1

I call R script from Python as follows:

 import rpy2.robjects as robjects
 robjects.r.source("C:\\Users\Name\Documents\compbdt.R", encoding="utf-8")

And my R script is below:

main <- function(N) {
  require(data.table)
  data <- fread("C:\\compbdt.csv", sep=",")
  for (i in 1:N) {
    s11 <- data[i, s11]
    s10 <- data[i, s10]
    s01 <- data[i, s01]
    s00 <- data[i, s00]
    r11 <- data[i, r11]
    r10 <- data[i, r10]
    r01 <- data[i, r01]
    r00 <- data[i, r00]
    
    compbdt(s11, s10, s01, s00, r11, r10, r01, r00)
  }
}

main(N)

compbdt is a function as well, I just haven't shown it there.

I need main function to loop N times. N is defined during Python code.

How can I pass N as an argument to call R script properly?

Arzental
  • 103
  • 6
  • This might be what along the lines of what you're looking for: https://stackoverflow.com/questions/52526092/passing-r-variables-to-a-python-script-with-reticulate – thehand0 Feb 12 '22 at 07:24
  • 1
    It offers "call Python from R" while I need exactly the opposite. – Arzental Feb 12 '22 at 07:31

1 Answers1

0

Use the reticulate package. Run your Python code in either an R Markdown file or source it using reticulate::source_python(). This creates a Python object in your R session called py. Access objects created in Python using the extract operator: py$N, for example, would correspond with an object named N created by your Python script.

library(reticulate)
# This is a python block
N = 2
# This is an R block
r_N <- py$N
main(r_N)
dlyng
  • 11
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 12 '22 at 19:31