Essential Guide To Translating Between Python and R | by Molly Liebeskind | Towards Data Science

As a native English speaker, when I started learning Spanish as a child, three key practices helped me go from awkwardly trying to translate my English words into Spanish to thinking and responding (occasionally even dreaming) directly in Spanish.
Connecting the new Spanish word to the English word I already knew. Drawing parallels between Spanish and English words enables me to quickly grasp the meaning of the new word.Repeating the word many times and using it in many different scenarios drilled the words into my mind.Leveraging contextual clues enabled me to better understand how and why the word is used over its synonyms.
Connecting the new Spanish word to the English word I already knew. Drawing parallels between Spanish and English words enables me to quickly grasp the meaning of the new word.
Repeating the word many times and using it in many different scenarios drilled the words into my mind.
Leveraging contextual clues enabled me to better understand how and why the word is used over its synonyms.
When you first learn to code, repetition and contextualizing are essential. Through consistent repetition, you begin to memorize the vocabulary and syntax. As you begin seeing the code used in different contextual environments, often through project development you are able to understand how and why different functions and techniques are used. But there isn’t necessarily an easy way to connect the new way of thinking to the language you speak, which means that you aren’t just memorizing a word but, instead you have to develop a new understanding of each programming concept. Even the first line of code you write, print(“Hello World!”) requires you to learn how the print function works, how the editor returns a print statement, and when to use quotation marks. When you learn a second programming language, you have the benefit of translating concepts from the language you know to the new language to learn more efficiently and quickly.
The world of data science is split between Python advocates and R enthusiasts. But rather than declaring a side, anyone who has learned one of these languages should capitalize on their advantage and dive into the other. There are infinite parallels between Python and R and with both languages at your disposal, you can solve challenges in the best way possible rather than the limiting yourself to half of the tool shed. Below is a simple guide to connecting R and Python for easy translation between the two. By making these connections, repeatedly interacting with the new language, and contextualizing with projects, anyone who understands either Python or R can quickly begin programming in the other.
Looking at the Python and R side-by-side, you can see that they function and appear very similar with only minor differences in their syntax.
Datatypes
# Python                              # Rtype()                                class()type(5) #int                          class(5) #numerictype(5.5) #float                      class(5.5) #numerictype('Hello') #string                 class('Hello') #charactertype(True) #bool                      class(True) #logical
Assigning variables
# Python                              # Ra = 5                                 a <- 5
Importing Packages
# Python                              # Rpip install packagename               install.packages(packagename)import packagename                    library(packagename)
Math: It’s the same — math is the same in all languages!
# Python                              # R+ - / *                               + - / *# The same goes for logical operators< #less than                          < #less than> #greater than                       > #greater than<= #less than or equal to             <= #less than or equal to== #is equal to                       == #is equal to!= #is not equal to                   != #is not equal to& #and                                & #and| #or                                 | #or
Calling a function
# Python                              # Rfunctionname(args, kwargs)            functionname(args, kwargs)print("Hello World!")                 print("Hello World!")
If / Else Statements
# Python                              # Rif True:                              if (TRUE) {    print('Hello World!')                 print('Go to sleep!')else:                                 } else {    print('Not true!')                    print('Not true!')                                       }
Lists & Vectors: This one is a bit of a stretch but I have found the connection to be helpful.
In python, a list is a mutable collection of ordered items of any datatype. Indexing a list in Python starts at 0 and is not inclusive.
In R, a vector is a a mutable collection of ordered items of the same type. Indexing a vector in R starts at 1 and is inclusive.
# Python                              # Rls = [1, 'a', 3, False]               vc <- c(1, 2, 3, 4)# Python indexing starts at 0, R indexing starts at 1b = ls[0]                             b = vc[1]print(b) #returns 1                   print(b) #returns 1c = ls[0:1]                           c = vc[1:2]print(c) #returns 1                   print(c) #returns 1, 2
For loops
# Python                              # Rfor i in range(2, 5):                 for(i in 1:10) {    a = i                                 a <- i }
Both python and R offer simple and streamlined data manipulation, making them essential tools for data scientists. Both languages are equipped with packages that enable loading, cleaning, and processing of data frames.
In python, pandas is the most common library used for loading and manipulating data frames using the DataFrame object.
In R, tidyverse is a similar library that enables simple data frame manipulation using the data.frame object.
Additionally, for streamlined code, both languages allow multiple operations to be piped together. In python, the . can be used to combine different operations while the %>% pipe is used in R.
Reading, Writing, and Viewing Data
# Python                              # Rimport pandas as pd                   library(tidyverse)# load and view datadf = pd.read_csv('path.csv')          df <- read_csv('path.csv')df.head()                             head(df)df.sample(100)                        sample(df, 100)df.describe()                         summary(df)# write to csvdf.to_csv('exp_path.csv')             write_csv(df, 'exp_path.csv')
Renaming & Adding Columns
# Python                              # Rdf = df.rename({'a': 'b'}, axis=1)    df %>% rename(a = b)df.newcol = [1, 2, 3]                 df$newcol <- c(1, 2, 3)df['newcol'] = [1, 2, 3]              df %>%                                          mutate(newcol = c(1, 2, 3))
Selecting and Filtering Columns
# Python                              # Rdf['col1', 'col2']                    df %<% select(col1,col2)df.drop('col1')                       df %<% select(-col1)
Filtering Rows
# Python                              # Rdf.drop_duplicates()                  df %<% distinct()df[df.col > 3]                        df %<% filter(col > 3)
Sorting Values
# Python                              # Rdf.sort_values(by='column')           arrange(df, column)
Aggregating Data
# Pythondf.groupby('col1')['agg_col').agg(['mean()']).reset_index()# Rdf %>%     group_by(col1) %>%     summarize(mean = mean(agg_col, na.rm=TRUE)) %>%    ungroup() #if resetting index
Aggregating With Filter
# Pythondf.groupby('col1').filter(lambda x: x.col2.mean() > 10)# Rdf %>%     group_by(col1) %>%     filter(mean(col2) >10)
Merging Data Frames
# Pythonpd.merge(df1, df2, left_on="df1_col", right_on="df2_col")# Rmerge(df1, df2, by.df1="df1_col", by.df2="df2_col")
The above examples are a starting point for creating mental parallels between Python and R. While most data scientists will lean towards one language or the other, being comfortable in both enables you to leverage the tools that best fit your needs.
Please leave any parallels that you have found helpful and additional comments below.