Use the data.frame() function in R to create a data frame from vectors.

The data frame in R is a two-dimensional array or table where each row contains the value of each column and the column contains the value for each variable. It can contain heterogeneous data. Vectors in R contain data of the same data type.

In this example, we will discuss how to create a data frame from vectors, add a new column vector to a data frame.

Create a Data Frame from Vectors

Let’s practice creating a data frame from vectors by creating the vectors.

Create vectors using the c() function in R.

name <- c("Tom","Kim","Sam","Julie","Emily","Chris")
gender <- c("Male", "Male", "Male", "Female")
age <- c(18, 20, 17, 21)
marks <- c(72,77,65,80,85,87)

In the above R code, we have defined 4 vectors name, gender, age, and marks. Each vector contains the data of the same data type.

For example, the name vector contains the character data type, and the age vector contains the numeric data type.

Create a data frame from from vectors using data.frame() function.

# Create a data frame using the data.frame function
student_info <- data.frame(
name,
age,
gender,
marks
)
# Print the class of data frame
class(student_info)

# Print the data frame
student_info

If you run the above R code, the data.frame function creates a data frame using the vectors created.

The output of the R code creates a data frame from specific vectors and prints the class and data frame.

[1] "data.frame"
   name age gender marks
1   Tom  18   Male    72
2   Kim  20   Male    77
3   Sam  17   Male    65
4 Julie  21 Female    80
5 Emily  23 Female    85
6 Chris  21   Male    87

Add new column vector to Data Frame

You can append a new column vector to the existing data frame.

To add a new column vector to a data frame, follow below steps:

Create a new column vector

# Create a vector to add new column
id <- c(1,2,3,4,5,5)

Add the new column vector to a data frame.

# Add new column vector to data frame
student_info$id <- id
# Print the data frame
student_info

The above R code will add a new column vector to an existing data frame.

The output of the above R code is:

   name age gender marks id
1   Tom  18   Male    72  1
2   Kim  20   Male    77  2
3   Sam  17   Male    65  3
4 Julie  21 Female    80  4
5 Emily  23 Female    85  5
6 Chris  21   Male    87  5

Conclusion

I hope the above article on how to create a data frame from vectors is helpful to you.

The data.frame() function is used to create a data frame from the vectors in R.