How to Create Data Frame in R: Syntax and Examples
In R, you create a data frame using the
data.frame() function by passing vectors of equal length as columns. Each vector becomes a column, and the function combines them into a table-like structure called a data frame.Syntax
The basic syntax to create a data frame is data.frame(column1 = vector1, column2 = vector2, ...). Each argument defines a column name and its values as a vector. All vectors must have the same length to form rows.
r
data.frame(column1 = c(value1, value2), column2 = c(value3, value4))
Example
This example creates a data frame with three columns: Name, Age, and City. It shows how to combine character and numeric vectors into a data frame.
r
df <- data.frame( Name = c("Alice", "Bob", "Charlie"), Age = c(25, 30, 35), City = c("New York", "Los Angeles", "Chicago") ) print(df)
Output
Name Age City
1 Alice 25 New York
2 Bob 30 Los Angeles
3 Charlie 35 Chicago
Common Pitfalls
Common mistakes include using vectors of different lengths, which causes an error, or forgetting to name columns, which results in default names like X1, X2. Also, mixing data types in a single vector can cause unexpected behavior.
r
## Wrong: vectors of different lengths # data.frame(Name = c("Alice", "Bob"), Age = c(25)) ## Right: vectors of equal length data.frame(Name = c("Alice", "Bob"), Age = c(25, 30))
Quick Reference
| Function | Description |
|---|---|
| data.frame() | Creates a data frame from vectors |
| c() | Combines values into a vector |
| print() | Displays the data frame content |
Key Takeaways
Use data.frame() with vectors of equal length to create a data frame.
Name each vector argument to set column names clearly.
Mixing data types in one vector can cause issues; keep columns consistent.
Always check vector lengths to avoid errors when creating data frames.