How to Create a Data Frame from Vector in R

To create a data frame from a vector, use the “data.frame()” method.

Each column is a vector, and all the columns make up the data frame.

The rows in a data frame represent observations, while the columns represent variables or features.

Visual Representation

Creating a Vector from data frame
Figure 1: Using data.frame() function to convert vectors to data frame

Here’s a step-by-step guide to how you can create a data frame using vectors:

Step 1: Create Vectors

Create vectors that will serve as the columns of your data frame.

vec1 <- c(1, 2, 3)
vec2 <- c(4, 5, 6)
vec3 <- c(7, 8, 9)

Step 2: Use data.frame() Function

After creating vectors, you must pass those vectors as column names to the data.frame() function.

df <- data.frame(col1 = vec1, col2 = vec2, col3 = vec3)

Step 3: View the data frame

You can view the data frame by typing its name or using the print() function.

print(df)

Now, see the output.

   col1 col2 col3
1   1    4    7
2   2    5    8
3   3    6    9

Get the Structure of a data frame

You can use the “str()” function to get the structure of a data frame.

vec1 <- c(1, 2, 3)
vec2 <- c(4, 5, 6)
vec3 <- c(7, 8, 9)

df <- data.frame(col1 = vec1, col2 = vec2, col3 = vec3)

str(df)

Output

Getting the Structure of a data frame

Adding columns and rows to a data frame

Adding a column

Adding new column to a data frame
Figure 2: Adding a new column to the data frame using the $ operator

To add a new column to the data frame, just add a new column vector in the data frame.

vec1 <- c(1, 2, 3)
vec2 <- c(4, 5, 6)
vec3 <- c(7, 8, 9)

df <- data.frame(col1 = vec1, col2 = vec2, col3 = vec3)
df

print("After adding a new column:")
df$col4 <- c(10, 11, 12)
df

Output

Output of Adding new column to a data frame

Adding rows

Adding rows to the data frame
Figure 3: Creating rows using vector and then appending to a data frame

To add a row in the data frame, use the rbind() function to append new rows to an existing data frame.

vec1 <- c(1, 2, 3)
vec2 <- c(4, 5, 6)
vec3 <- c(7, 8, 9)

df1 <- data.frame(col1 = vec1, col2 = vec2, col3 = vec3)
df1

vec11 <- c(10, 11)
vec21 <- c(12, 13)
vec31 <- c(14, 15)

print("After adding two new rows:")
df2 <- data.frame(col1 = vec11, col2 = vec21, col3 = vec31)
df <- rbind(df1, df2)
df

Output

Output of adding rows in R

You can see that we added a new column and two new rows by creating vectors. Each column of a data frame is a vector, and a group of columns will create a single data frame.

Leave a Comment