R Program to create a data frame from four given vectors

How to create a data frame from four given vectors

Here we are explaining how to write an R program to create a data frame from four given vectors. Here we are using a built-in function data.frame() for this. A data frame is used for storing data tables which has a list of vectors with equal length. The data frames are created by function data.frame(), which has tightly coupled collections of variables. The syntax of this function is 



data.frame(…, row.names = NULL, check.rows = FALSE,check.names = TRUE, fix.empty.names = TRUE,stringsAsFactors = default.stringsAsFactors()) 

Where dots(...) indicates the arguments are of either the form value or tag = value and row. name is a NULL or a single integer or character string.

How to create a data frame from four given vectors in the R program

Below are the steps used in the R program to create a data frame from four given vectors. In this R program, we directly give the data frame to a built-in function. Here we are using variables N, S, A, Q for holding different types of vectors. Call the function data.frame() for creating dataframe.

ALGORITHM

STEP 1: Assign variables N,S,A,Q with vector values 

STEP 2: First print original vector values

STEP 3: Call the function data frame as data.frame(N, S, A, Q) 

STEP 4: Assign variable DF with the result of data.frame function

STEP 5: print the variable DF which holding the result 

R Source Code

                                          N = c('Jhon', 'Michel', 'Albert', 'James', 'Kevin')
S= c(10, 9.2, 14, 12.5,18)
A = c(1, 3, 2, 3, 2)
Q= c('yes', 'no', 'yes', 'no', 'no')
print("Original data frame:")
print(N)
print(S)
print(A)
print(Q)
DF = data.frame(N, S, A, Q)  
print(DF)
                                      

OUTPUT

[1] "Original data frame:"
 [1] "Jhon" "Michel" "Albert" "James" "Kevin"  
 [1] 10  9.2  14  12.5  18
 [1] 1 3 2 3 2 
 [1] "yes" "no"  "yes" "no"  "no"
     N       S      A    Q
1  Jhon      10     1   yes
2  Michel    9.2    3   no
3  Albert    14     2   yes
4  James     12.5   3   no
5  Kevin     18     2   no