R Programming: Convert Dataframe columns to Vectors
R Programming: Vector Exercise-16 with Solution
Write a R program to convert given dataframe column(s) to a vector.
Sample Solution :
R Programming Code :
# Create a vector named dfc1 with elements 1 through 5
dfc1 = c(1, 2, 3, 4, 5)
# Create a vector named dfc2 with elements 6 through 10
dfc2 = c(6, 7, 8, 9, 10)
# Create a vector named dfc3 with elements 11 through 15
dfc3 = c(11, 12, 13, 14, 15)
# Create a vector named dfc4 with elements 16 through 20
dfc4 = c(16, 17, 18, 19, 20)
# Combine the vectors into a dataframe with column names dfc1, dfc2, dfc3, and dfc4
v <- data.frame(dfc1=1:5, dfc2=6:10, dfc3=11:15, dfc4=16:20)
# Print the dataframe to the console
print(v)
Output:
dfc1 dfc2 dfc3 dfc4 1 1 6 11 16 2 2 7 12 17 3 3 8 13 18 4 4 9 14 19 5 5 10 15 20
Explanation:
- dfc1 = c(1, 2, 3, 4, 5)
- Creates a vector named dfc1 with the elements 1, 2, 3, 4, and 5.
- dfc2 = c(6, 7, 8, 9, 10)
- Creates a vector named dfc2 with the elements 6, 7, 8, 9, and 10.
- dfc3 = c(11, 12, 13, 14, 15)
- Creates a vector named dfc3 with the elements 11, 12, 13, 14, and 15.
- dfc4 = c(16, 17, 18, 19, 20)
- Creates a vector named dfc4 with the elements 16, 17, 18, 19, and 20.
- v <- data.frame(dfc1=1:5, dfc2=6:10, dfc3=11:15, dfc4=16:20)
- Creates a dataframe v with four columns (dfc1, dfc2, dfc3, and dfc4), where each column contains the values from the corresponding vectors.
- print(v)
- Displays the dataframe v in the console
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to find common elements from multiple vectors.
Next: Write a R program to extract every nth element of a given vector.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/r-programming-exercises/vector/r-programming-vector-exercise-16.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics