Let’s learn how to create variables and understand different data types in both languages.
Defining Variables
Both R and Python allow you to create variables easily without declaring their type explicitly.
Exercise 1
Create different types of variables
# Define variables in Python
a = 2
b = 5.0
x = 'hello world'
print(a)
print(b)
print(x)
# Calculate with variables
e = a * 2 + b
print(f"Result: {e}")
# Define variables in R
a = 2
b = 5.0
x = 'hello world'
print(a)
print(b)
print(x)
# Calculate with variables
e = a * 2 + b
print(paste("Result:", e))
Checking Variable Types
You can check the type of any variable using built-in functions.
Exercise 2
Explore variable types
# Check types in Python
a = 2
b = 5.0
x = 'hello world'
is_true = True
print(type(a)) # int
print(type(b)) # float
print(type(x)) # str
print(type(is_true)) # bool
# Check types in R
a = 2
b = 5.0
x = 'hello world'
is_true = TRUE
print(typeof(a)) # double
print(typeof(b)) # double
print(typeof(x)) # character
print(typeof(is_true)) # logical
Type Conversion
Sometimes you need to convert between types.
Exercise 3
Convert between different types
# Type conversion in Python
num_str = "42"
num_int = int(num_str)
num_float = float(num_str)
print(f"String: {num_str}, type: {type(num_str)}")
print(f"Integer: {num_int}, type: {type(num_int)}")
print(f"Float: {num_float}, type: {type(num_float)}")
# Convert number to string
value = 100
value_str = str(value)
print(f"Converted: {value_str}, type: {type(value_str)}")
# Type conversion in R
num_str = "42"
num_int = as.integer(num_str)
num_float = as.numeric(num_str)
print(paste("String:", num_str, ", type:", typeof(num_str)))
print(paste("Integer:", num_int, ", type:", typeof(num_int)))
print(paste("Float:", num_float, ", type:", typeof(num_float)))
# Convert number to string
value = 100
value_str = as.character(value)
print(paste("Converted:", value_str, ", type:", typeof(value_str)))
Key Differences
- Python uses
int,float,str,boolas basic types - R uses
integer,double,character,logicalas basic types - Python uses
type()to check types, R usestypeof()orclass() - Python type conversion:
int(),float(),str() - R type conversion:
as.integer(),as.numeric(),as.character()