Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
This post was inspired by one of Thomas Neitmann’s posts showing how to write some debugging code in R and Python to automatically search code errors on StackOverflow. Below is a simpler example where we do this with Amazon’s site.
In this blog we are going to write code that is as similar as possible to each other and use R and Python to search for what we want to find on Amazon.ca. In our example we are going to look for a coffee machine.
The Code:
This is a breakdown of the code, we are going to time the code being ran from once the necessary libraries are loaded in (for Python) to the end of the execution. We are going to define a start time as our system time before running the code.
Running the Code
R Code
start_time<-Sys.time() search_amazon_basic<- function(what){ browseURL(paste0("https://www.amazon.ca/s?k=",what)) } search_amazon_basic("Coffee Machine") print(paste("--",Sys.time()-start_time,"seconds --"))
Output:
[1] "-- 0.0299808979034424 seconds --"
Python Code
import webbrowser import time start_time=time.time() def search_amazon_basic(what): webbrowser.open_new(f"https://www.amazon.ca/s?k={what}") search_amazon_basic("Coffee Machine") print("--- %s seconds ---" % (time.time() - start_time))
Output:
--- 0.10091876983642578 seconds ---
Huh! Well, will you look at that! R was a little more than 3 times faster than Python. My best guess for why there is such a time gap is because python needs to reference its imported libraries before executing the required operation, as opposed to R which has it built in to the Base package.
Conclusion
This is just a very small example comparing R to Python. It seems like both programs were able to do the same task with relative ease. Python needed to have the webbrowser
module imported for its code whereas R did not require any libraries even for timing the operation–whereas python required the time
module for that.
Once again, thank you Thomas Neitmann for giving me this inspiration! If you like this, please be sure to check out Thomas out on LinkedIn and his blog on R Progamming.
Have you done this and have a faster way to do this on Python versus R? Please let me know in a comment so I can try it out!
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.