library(reticulate) # to use python in RStudio
library(tidyverse) # data wrangling and plotting with R
R code chunks are in light pink, while python in light blue.
bit64 package provides support for them.(more here)Interesting differences as demonstrated in the following code chunks
a = 5
type(a)
## <class 'int'>
b = 5.0
type(b)
## <class 'float'>
boolP = TRUE # in Python, boolean type values should only have the first letter capitalized
## Error in py_call_impl(callable, dots$args, dots$keywords): NameError: name 'TRUE' is not defined
##
## Detailed traceback:
## File "<string>", line 1, in <module>
boolP = True
a <- 5
class(a)
## [1] "numeric"
b <- 5.0
class(b)
## [1] "numeric"
# specifically require the integer class
c <- 5L
class(c)
## [1] "integer"
logicR <- True # in R, logic type values should have all letters capitalized
## Error in eval(expr, envir, enclos): object 'True' not found
logicR <- TRUE
In the above code chunks, “=” is used to assign values in Python, while “<-” is used in R.
Actually, you can also use “=” in R, but “=” and “<-” have different results:
# calculate the sum of a vector ranging from 1 to 10
sum(x = 1:10)
## [1] 55
# this results in an error because x only exists within the scope of the function
x
## Error in eval(expr, envir, enclos): object 'x' not found
# same function, this time use "<-" instead of "=" to assign the vector
sum(x <- 1:10)
## [1] 55
x
## [1] 1 2 3 4 5 6 7 8 9 10
Interesting differences as demonstrated in the following code chunks
x="cute"
y="bunny"
z="hop"
x + y
## 'cutebunny'
z * 5
## 'hophophophophop'
With reticulate package, It is easy to apply R code on an object created in python code chunks, simply use py$python_object_created.
# call object x created in the above Python code chunk
py$x
## [1] "cute"
# adding or multiply strings in R creates error
py$x + py$y
## Error in py$x + py$y: non-numeric argument to binary operator
py$z * 5
## Error in py$z * 5: non-numeric argument to binary operator
# to paste two strings, you use paste() or paste0()
paste(py$x,py$y)
## [1] "cute bunny"
paste0(py$x,py$y)
## [1] "cutebunny"