Repository navigation
Expand file tree
/
Copy pathpython_rmd.Rmd
More file actions
168 lines (124 loc) · 4.36 KB
/
Copy pathpython_rmd.Rmd
File metadata and controls
168 lines (124 loc) · 4.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
---
title: "Python in R Markdown"
output:
github_document:
toc: true
authors: "Tiffany Timbers and modified by Kewalin Samart"
editor_options:
markdown:
wrap: 72
---
To use Python in R Markdown, we need to load the
{[reticulate](https://rstudio.github.io/reticulate/)} R package in a
code chunk, we do it here in the setup code chunk. We also load the
{[ggplot2](https://ggplot2.tidyverse.org/)} R package so we can plot
some data from a Python `pandas` data frame later on!
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(reticulate)
library(ggplot2)
```
## Python in `.Rmd` files
### Load libraries
Just like R, you can use Python in `.Rmd` files! Here we import the
Python package that we need to import our data into Python, `pandas`.
`pandas` is a Python package that adds data reading, wrangling, and
simple data visualization functionality to Python where sometimes depend
on `matplotlib` functions. It holds a similar place as the {tidyverse} R
meta-package does (however `pandas` is not a meta-package, just a very
large package). If you want to learn more about pandas, see the "[10
minutes to
pandas](https://pandas.pydata.org/pandas-docs/stable/user_guide/10min.html)"
in the docs our checkout this free interactive course:
<https://prog-learn.mds.ubc.ca/en>.
To [install Python
packages](https://rstudio.github.io/reticulate/articles/python_packages.html)
please run the cell below
```{r}
py_config() # optional: to check python configuration setups
py_install("pandas") # install pandas
py_install("matplotlib") # install matplotlib
```
### Downgrade pandas and numpy version
#### to make later python\<-\>R conversions possible
ref: <https://github.com/rstudio/reticulate/issues/1620>
```{r downgrade}
reticulate::py_install(c("pandas<2.2.2", "numpy<2.0"), ignore_installed = TRUE)
```
```{python libraries}
import pandas as pd
import matplotlib.pyplot as plt
```
### Load data
Let's load the titanic data (which lives in the `data` directory of this
project) and view the data:
```{python data}
titanic = pd.read_csv("data/titanic.csv")
```
### plot data
#### Using Python and `pandas`
First, let's use some quick and simple `pandas` plotting functions:
```{python python-plot}
titanic.plot.scatter(x='age', y='fare', alpha=0.3)
plt.show()
```
Want to learn more about getting started plotting in Python using
`pandas`, see this page to get started:
<https://pandas.pydata.org/pandas-docs/stable/user_guide/visualization.html>
#### Using R and {ggplot2}
We can also access the Python environment in this R Markdown document
from R! This allows us to apply R's functions on our Python objects! We
can use the `py$obbject` syntax to do this and create a data
visualization using {ggplot2}!
```{r r-plot, warning=FALSE, fig.height=4, fig.width=4}
ggplot2::ggplot(py$titanic, aes(x = age, y = fare)) +
geom_point()
```
### Subsetting data in `pandas`
Here we subset the age and fare columns:
```{python}
titanic[["age", "fare"]]
```
Here we filter for rows containing passengers who's age was 70 or
greater:
```{python}
titanic[titanic["age"] > 70]
```
Here we find the destination of the first passenger:
```{python first destination}
first_dest = titanic["home.dest"][0]
first_dest
```
Why 0 as the numerical index above? Python counts from 0, not 1!
### And inline python code within markdown text!
We can use the R Markdown inline syntax and the `py$` syntax to reach
into the Python environment and access the `first_dest` python object
(which is a string).
The destination of the first passenger is `r py$first_dest`.
### Sourcing a Python script
#### Example 1: `greeting.py` (contains a function named greeting with Python code to call the function within the same script)
```{r}
# source the Python script
source_python('greeting.py')
# call the Python function and pass a new name
greeting("Kewalin")
```
#### Example 2: `titanic.py` (only contains a function named read_titanic)
```{r}
# source the Python script
source_python("titanic.py")
# call the Python function and pass the Titanic dataset
titanic <- read_titanic("data/titanic.csv")
# load ggplot2 for visualization
library(ggplot2)
# plot the Titanic data
ggplot(titanic, aes(x = age, y = fare, color = as.factor(survived))) +
geom_point(alpha = 0.6) +
labs(
title = "Age vs Fare (Colored by Survival)",
x = "Age",
y = "Fare",
color = "Survived"
) +
theme_minimal()
```