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:")
## [1] "Original data frame:"
print(N)
## [1] "Jhon"   "Michel" "Albert" "James"  "Kevin"
print(S)
## [1] 10.0  9.2 14.0 12.5 18.0
print(A)
## [1] 1 3 2 3 2
print(Q)
## [1] "yes" "no"  "yes" "no"  "no"
DF = data.frame(N, S, A, Q)  
print(DF)
##        N    S A   Q
## 1   Jhon 10.0 1 yes
## 2 Michel  9.2 3  no
## 3 Albert 14.0 2 yes
## 4  James 12.5 3  no
## 5  Kevin 18.0 2  no

R Source Code

N = c('Jhon', 'Michel', 'Albert', 'James', 'Kevin', 'Pappu')
S = c(10, 9.2, 14, 12.5, 18, 21)
A = c(1, 3, 2, 3, 2, 1)
Q = c('yes', 'no', 'yes', 'no', 'no', 'yes')

print("Original data frame:")
## [1] "Original data frame:"
print(N)
## [1] "Jhon"   "Michel" "Albert" "James"  "Kevin"  "Pappu"
print(S)
## [1] 10.0  9.2 14.0 12.5 18.0 21.0
print(A)
## [1] 1 3 2 3 2 1
print(Q)
## [1] "yes" "no"  "yes" "no"  "no"  "yes"
DF = data.frame(N, S, A, Q)  
print(DF)
##        N    S A   Q
## 1   Jhon 10.0 1 yes
## 2 Michel  9.2 3  no
## 3 Albert 14.0 2 yes
## 4  James 12.5 3  no
## 5  Kevin 18.0 2  no
## 6  Pappu 21.0 1 yes