0

I'm trying to write a simple python function like adding 5 to every item in a column, but I am unable to define a python function within the R environment. Is it possible to define a Python function within here?

library(magrittr)
library(dplyr)
library(reticulate)

os <- import('os')
pd <- import('pandas', convert = F)
np <- import('numpy', convert = F)

a <- pd$Series(data = c(1, 2, 3))

b <- pd$DataFrame(list(a = c(10,20,30),
                       b = c(20, 30, 10)))

c <- pd$DataFrame(list(a = c(10,20,30),
                       c = c(40, 50, 60)))$merge(b)

c$cumsum()

plus_5 <- function(x) x + 5

c$apply(func = plus_5(b$a))
maloneypatr
  • 3,562
  • 4
  • 23
  • 33

1 Answers1

0

You can define a Python function within R and call it like the following:

library(reticulate)
util <- py_run_string("
def f1(a, b=3):
  return a + b
")
util$f1(1)

You can then use it in your c$apply(). Hope this helps.

Yuan Tang
  • 696
  • 4
  • 15