What are the primary differences between R Arrays and R Data Frames?
Answer:
Explanation:
The primary differences between R arrays and R data frames are their dimensionality and the type of data they store. Arrays are multi-dimensional and store elements of the same type, making them suitable for tasks like mathematical computations across multiple dimensions. Data frames, on the other hand, are two-dimensional and can store elements of different types, which makes them ideal for storing and analyzing tabular data.
# Creating an array (3D)
my_array <- array(1:24, dim = c(2, 3, 4))
# Creating a data frame
my_data_frame <- data.frame(
Name = c("Alice", "Bob", "Charlie"),
Age = c(25, 30, 35),
Salary = c(50000, 60000, 70000)
)
# Printing the array
print(my_array)
# Printing the data frame
print(my_data_frame)
In this example, my_array
is a 3D array storing numeric data, while my_data_frame
is a data frame storing mixed data types across rows and columns. Arrays are more suited for tasks involving uniform data across multiple dimensions, whereas data frames are better for heterogeneous data that needs to be organized into a tabular format.