Create a data frame Using the data.frame() Function
The most common method to create a data frame in R is by using the data.frame() function. This function takes vectors as input and combines them into a data frame.
# Creating vectors
name <- c("Johny", "Ali", "Boby", "Emilya")
age <- c(25, 30, 22, 28)
salary <- c(50000, 60000, 45000, 55000)
# Creating a dataframe
df <- data.frame(Name = name, Age = age, Salary = salary)
# Displaying the dataframe
print(df)
Output:
Name Age Salary
1 Johny 25 50000
2 Ali 30 60000
3 Boby 22 45000
4 Emilya 28 55000
In this example, we create vectors for name, age, and salary, and then use the data.frame() function to combine them into a dataframe called df.
How to create dataframe in R
Dataframes are fundamental data structures in R for storing and manipulating data in tabular form. They allow you to organize data into rows and columns, similar to a spreadsheet or a database table. Creating a data frame in the R Programming Language is a simple yet essential task for data analysis and manipulation. In this article, we’ll explore different methods to create data frames in R.