R Programming: Add a new column in a given data frame
R Programming: Data frame Exercise-8 with Solution
Write a R program to add a new column in a given data frame.
Sample Solution:
R Programming Code:
exam_data = data.frame(
name = c('Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'),
score = c(12.5, 9, 16.5, 12, 9, 20, 14.5, 13.5, 8, 19),
attempts = c(1, 3, 2, 3, 2, 3, 1, 1, 2, 1),
qualify = c('yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes')
)
print("Original dataframe:")
print(exam_data)
print("New data frame after adding the 'country' column:")
exam_data$country = c("USA","USA","USA","USA","USA","USA","USA","USA","USA","USA")
print(exam_data)
Sample Output:
[1] "Original dataframe:" 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 [1] "New data frame after adding the 'country' column:" name score attempts qualify country 1 Anastasia 12.5 1 yes USA 2 Dima 9.0 3 no USA 3 Katherine 16.5 2 yes USA 4 James 12.0 3 no USA 5 Emily 9.0 2 no USA 6 Michael 20.0 3 yes USA 7 Matthew 14.5 1 yes USA 8 Laura 13.5 1 no USA 9 Kevin 8.0 2 no USA 10 Jonas 19.0 1 yes USA
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to extract 3rd and 5th rows with 1st and 3rd columns from a given data frame.
Next: Write a R program to add new row(s) to an existing data frame.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook