R Data Frames
Data frames in R are used to store tabular data. They are similar to matrices but can contain columns of different data types, making them ideal for datasets.
Key Topics
Data Frame Creation
Data frames can be created using the data.frame()
function.
# Creating a data frame
my_data_frame <- data.frame(
Name = c("Alice", "Bob", "Charlie"),
Age = c(25, 30, 35),
Score = c(85, 90, 95)
)
print(my_data_frame)
Output:
Name Age Score
1 Alice 25 85
2 Bob 30 90
3 Charlie 35 95
1 Alice 25 85
2 Bob 30 90
3 Charlie 35 95
Code Explanation: The data.frame()
function creates a data frame with three columns: Name
, Age
, and Score
.
Accessing Data Frame Elements
You can access elements of a data frame using the dollar sign ($
) or square brackets.
# Accessing columns
names_column <- my_data_frame$Name
# Accessing specific elements
age_value <- my_data_frame[2, "Age"]
print(names_column)
print(age_value)
Output:
[1] "Alice" "Bob" "Charlie"
[1] 30
[1] 30
Code Explanation: The $
operator is used to access the Name
column. The square brackets are used to access the second row and Age
column.
Key Takeaways
- Data frames store tabular data and can have columns of different data types.
- The
data.frame()
function is used to create data frames. - Access elements using the
$
operator or square brackets.