2

I am trying to execute a python code in Rstudio (Rmarkdown) in a python chunk and I cannot declare a function while I am getting an error:

IndentationError: unexpected indent (, line 1)

(I am not mixing tabs with spaces or so)

The following code doesn't work in Rstudio's python chunk but works perfectly fine in Python Spyder IDE.

import pandas as pd

cars = {'Brand': ['1HondaA','2ToyotaA','3FordA','4AudiA'],
        'Brand_2': ['1HondaA','2ToyotaA','3FordA','4AudiA']
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Brand_2'])
df

def convert(brand_column):
  df[brand_column] = df[brand_column].str.replace('A', '')
  df[brand_column + "_number"] = df[brand_column].str.extract('(\d+)')


convert("Brand")
df
convert("Brand_2")
df

Screen: enter image description here

Sin
  • 135
  • 1
  • 9

1 Answers1

1

You are needing to specify where you python is located. I am on a mac so here is how I can to do it. Your indent error did not occur to me, so maybe double check your indents and spaces.

---
output: html_document
---

```{r}
library(reticulate)
knitr::knit_engines$set(python = reticulate::eng_python)
use_python("/usr/local/bin/python3")
```

```{python}

import pandas as pd

cars = {'Brand': ['1HondaA','2ToyotaA','3FordA','4AudiA'],
        'Brand_2': ['1HondaA','2ToyotaA','3FordA','4AudiA']
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Brand_2'])
df

def convert(brand_column):
  df[brand_column] = df[brand_column].str.replace('A', '')
  df[brand_column + "_number"] = df[brand_column].str.extract('(\d+)')


convert("Brand")
df
convert("Brand_2")
df
```    

enter image description here

If you have windows, it might be similar to "C:\\Users\\username\\Anaconda3\\python.exe") or such

Daniel_j_iii
  • 3,041
  • 2
  • 11
  • 27
  • Thank you for your answer! I realized that, in fact, it works while you Knit the whole RMarkdown document at once. However, did you try to execute the code line by line (or chunk by chunk)? While doing so, the error still appears in my case (and yes, I checked for indents and spaces). – Sin Nov 13 '20 at 11:55
  • not really, but [a few people](https://stackoverflow.com/questions/49503195/reticulate-running-python-chunks-in-rmarkdown) have work arounds and use reticulate functions in other situations. – Daniel_j_iii Nov 13 '20 at 13:58