Basic operators in R and Python | Macarena Quiroga

Basic operators in R and Python

In this blogpost we will show the basic operators in R and Python

In this blogpost you’ll find the differences and similarities in the basic operators of R and Python.


Arithmetic Operators

OperationRPython
Sum5 + 35 + 3
Substraction5 - 35 - 3
Multiplication5 * 35 * 3
Division5 / 35 / 3
Exponentiation5 ^ 35 ** 3
Integer division5 %/% 35 // 3
Modulus.5 %% 35 % 3

The first four operators (addition, subtraction, multiplication, and division) are performed in the same way; the differences appear in exponentiation, integer division, and modulus.


Assignment Operator

In R, you can assign names to objects in two interchangeable ways:

num <- 4
num2 = 6


In Python, only the equal sign is used, but two additional operators are also used:

num3 = 1
num3 += 3 # reassigns to 'num3' by adding 3
num3 *=2 # reassigns to 'num3' by multiplying it by 3


These last two operators take the object (in this case, num3 which starts with a value of 1) and reassign a value to it from an arithmetic operation. So, in the first case, num3 becomes 4 (1 from the original value, + 3 from the new reassignment operation). In the second case, we start from the value of 4 and multiply it by 2, resulting in num3 becoming 8.


Relational operators

The relational operators are identical in both languages.

3 > 5 # evaluates if 3 is bigger than 5, FALSE
3 >= 5 # evaluates if 3 is bigger than or equal to 5, FALSE
3 < 5 # evaluates if 3 is smaller than 5, TRUE
3 <= 5 # evaluates if 3 is smaller than or equal to 5, TRUE
3 != 5 # evaluates if 3 is different from 5, TRUE
3 == 5 # evaluates if 3 is equal to 5, FALSE


Logic operators

This is where we find the biggest differences, because R uses symbols and Python uses reserved words to evaluate statements.

a = 3
b = 5


OperationRPython
Not (negation)!a < 2not a < 2
And (both conditions must be true)a < 2 & b > 4a < 2 and b > 4
Or (only one can be true)a < 2 | b > 4a < 2 or b > 4


In these cases, the first and second rows evaluate to FALSE, while the third row evaluates to TRUE.

Closing

Exploring the basic operators in R and Python has provided invaluable insights into the fundamental building blocks of these programming languages. Understanding their similarities and differences empowers developers to leverage the full potential of each language and enhance their coding proficiency.

As always, remember you can suscribe to my blog to stay updated, and if you have any questions, don’t hesitate to contact me. And if you like what I do, you can buy me a cafecito from Argentina or a kofi.

Macarena Quiroga
Macarena Quiroga
Linguist/PhD student

I research language acquisition. I’m looking to deepen my knowledge of statistis and data science with R/Rstudio. If you like what I do, you can buy me a coffee from Argentina, or a kofi from other countries. Suscribe to my blog here.

Related