R Program to Create a Data Frame

Introduction

A data frame is one of the most commonly used data structures in R, designed to store tabular data. It can hold different types of data (numeric, character, etc.) in its columns, making it used for data analysis. This guide will walk you through writing an R program to create a data frame.

Problem Statement

Create an R program that:

  • Creates a data frame with multiple columns of different data types.
  • Displays the created data frame.

Example:

  • Input: Columns for Name, Age, Gender, and Score.
  • Output: A data frame containing these columns with corresponding data.

Solution Steps

  1. Create the Data: Define vectors for each column in the data frame.
  2. Create the Data Frame: Use the data.frame() function to combine these vectors into a data frame.
  3. Display the Data Frame: Use the print() function to display the created data frame.

R Program

# R Program to Create a Data Frame
# Author: Ramesh Fadatare

# Step 1: Create the data for each column
names <- c("Ramesh", "Suresh", "Mahesh", "Ganesh")
ages <- c(25, 30, 22, 28)
genders <- c("Male", "Male", "Male", "Male")
scores <- c(85.5, 90.0, 88.5, 92.0)

# Step 2: Create the data frame
students_data <- data.frame(Name = names, Age = ages, Gender = genders, Score = scores)

# Step 3: Display the data frame
print("Students Data Frame:")
print(students_data)

Explanation

Step 1: Create the Data for Each Column

  • Vectors names, ages, genders, and scores are created to hold the data for each column in the data frame. Each vector represents a different type of data (character, numeric, etc.).

Step 2: Create the Data Frame

  • The data.frame() function is used to create the data frame students_data, combining the vectors into a tabular format. Each vector becomes a column in the data frame, with the names Name, Age, Gender, and Score used as column headers.

Step 3: Display the Data Frame

  • The print() function is used to display the data frame, showing the data in a structured format.

Output Example

Example:

[1] "Students Data Frame:"
     Name  Age Gender Score
1  Ramesh  25  Male  85.5
2  Suresh  30  Male  90.0
3  Mahesh  22  Male  88.5
4  Ganesh  28  Male  92.0

Conclusion

This R program demonstrates how to create a data frame using the data.frame() function. It covers the creation of vectors, combining them into a data frame, and displaying the result. Data frames are essential in data analysis and manipulation in R, making this example valuable for anyone learning R programming. Understanding how to create and work with data frames is crucial for effectively handling and analyzing data in R.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top