All labs · lesson 2 of 9

R vs Pythonbeginner12 min

R/Python Comparison: Variables & Types

Understand how to work with variables and data types in both R and Python

Edit any code block and press Run (or Ctrl/⌘ + Enter, or Shift + Enter). The code runs in your browser, so there is nothing to install. The first run downloads the language once; later runs are instant.

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, bool as basic types
  • R uses integer, double, character, logical as basic types
  • Python uses type() to check types, R uses typeof() or class()
  • Python type conversion: int(), float(), str()
  • R type conversion: as.integer(), as.numeric(), as.character()