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
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
Adding columns and rows to a data frame
Adding a column
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
Adding rows
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
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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.