Create a Data Frame from four Vectors in R Programming
Write a R program to create a data frame from four given vectors.
Sample Solution:
R Programming Code:
# Create a vector containing names
name = c('Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas')
# Create a vector containing scores
score = c(12.5, 9, 16.5, 12, 9, 20, 14.5, 13.5, 8, 19)
# Create a vector containing attempts
attempts = c(1, 3, 2, 3, 2, 3, 1, 1, 2, 1)
# Create a vector containing qualification status
qualify = c('yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes')
# Print a message indicating the original data
print("Original data frame:")
# Print each vector
print(name)
print(score)
print(attempts)
print(qualify)
# Combine the vectors into a data frame
df = data.frame(name, score, attempts, qualify)
# Print the resulting data frame
print(df)
Output:
[1] "Original data frame:"
[1] "Anastasia" "Dima" "Katherine" "James" "Emily" "Michael"
[7] "Matthew" "Laura" "Kevin" "Jonas"
[1] 12.5 9.0 16.5 12.0 9.0 20.0 14.5 13.5 8.0 19.0
[1] 1 3 2 3 2 3 1 1 2 1
[1] "yes" "no" "yes" "no" "no" "yes" "yes" "no" "no" "yes"
name score attempts qualify
1 Anastasia 12.5 1 yes
2 Dima 9.0 3 no
3 Katherine 16.5 2 yes
4 James 12.0 3 no
5 Emily 9.0 2 no
6 Michael 20.0 3 yes
7 Matthew 14.5 1 yes
8 Laura 13.5 1 no
9 Kevin 8.0 2 no
10 Jonas 19.0 1 yes
Explanation:
- Create a vector named name: Contains the names of 10 individuals.
- Create a vector named score: Contains the scores corresponding to each individual.
- Create a vector named attempts: Contains the number of attempts made by each individual.
- Create a vector named qualify: Indicates whether each individual has qualified ("yes" or "no").
- Print a message: Displays "Original data frame:" to indicate the start of the data frame output.
- Print the name vector: Shows the names of the individuals.
- Print the score vector: Shows the scores of the individuals.
- Print the attempts vector: Shows the number of attempts for each individual.
- Print the qualify vector: Displays the qualification status for each individual.
- Create a data frame named df: Combines the name, score, attempts, and qualify vectors into a structured data frame.
- Print the data frame df: Displays the combined data frame containing all the information for each individual
Go to:
PREV : Write a R program to create an empty data frame.
NEXT :
Write a R program to get the structure of a given data frame.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
