This R program will help you to create a data frame from the given vectors.
A data frame is used for storing data tables which has a list of vectors with equal length. It is a matrix-like structure with different types of values or we can say that it is a table of data. It consists of vectors of the same length as columns in a table.
Here we are explaining how to write an R program to create a data frame from four given vectors. We can use a built-in function data.frame()
for creating a data frame in R. The function data.frame()
creates data frames that have 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.names
is a NULL or a single integer or character string.
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 contestant, points, tries, win for holding different types of vectors. Call the function data.frame()
for creating a data frame.
STEP 1: Assign variables contestant,points,tries,win with vector values
STEP 2: First print
original vector values
STEP 3: Call the in-built function data.frame(contestant,points,tries,win)
and assign the result of the function to variable df
STEP 4: print
the data frame df
contestant = c('John', 'Michael', 'Albert', 'James', 'Kevin')
points= c(10, 9.2, 14, 12.5,18)
tries = c(1, 3, 2, 3, 2)
win= c('yes', 'no', 'yes', 'no', 'no')
print("Original data frame:")
print(contestant)
print(points)
print(tries)
print(win)
df = data.frame(contestant,points,tries,win)
print(df)
[1] "Original data frame:" [1] "John" "Michael" "Albert" "James" "Kevin" [1] 10.0 9.2 14.0 12.5 18.0 [1] 1 3 2 3 2 [1] "yes" "no" "yes" "no" "no" contestant points tries win 1 John 10.0 1 yes 2 Michael 9.2 3 no 3 Albert 14.0 2 yes 4 James 12.5 3 no 5 Kevin 18.0 2 no