Using R and Python Together

May 8, 2021   

Have you ever wanted to see how a word looks scrambled up? Maybe not, but STILL python can do this.

first = "Sareen" 
last = "Ali"

first + last
## 'SareenAli'
last[0]+first[1:]+ ' ' +first[0]+last[1:]
## 'Aareen Sli'
2*(first[0:4]+last[-4:])
## 'SareAliSareAli'

It’s kinda funny.

Here’s how the two interact

# R chunk 
heyy <- "Hey there"
library(reticulate)
#Python Code Chunk 

hey = "people" 
print(r.heyy,hey)
## Hey there people
#R chunk 
cat(c(heyy,py$hey))
## Hey there people

Here’s an example from the slides using numbers.

We wanted to take mat1 from python and, in R, compute the inverse. Then, we wanted to send it back to python, and multiply it with mat1.

#Python Code Chunk 
import numpy as np
x=np.array([1,2,3])
mat1=np.array([[1,2],[3,4]])
#R Code Chunk 
mat2<- solve(py$mat1)
mat2
##      [,1] [,2]
## [1,] -2.0  1.0
## [2,]  1.5 -0.5
#Python Code Chunk 
np.dot(mat1,r.mat2).round()
## array([[1., 0.],
##        [0., 1.]])

And, it worked!!

Here’s a pic of a kitten that I think is so adorable!! :’)

Link to project 1

Link to google



comments powered by Disqus