R Programming: Convert two columns of a data frame to a named vector
R Programming: Vector Exercise-23 with Solution
Write a R program to convert two columns of a data frame to a named vector.
Sample Solution :
R Programming Code :
df = data.frame(code = c("R","G","W","B"),
name = c("Red", "Green", "White", "Black")
)
print("Original vector:")
print(df)
result = setNames(as.character(df$name), df$code)
print(result)
Sample Output:
[1] "Original vector:" code name 1 R Red 2 G Green 3 W White 4 B Black R G W B "Red" "Green" "White" "Black"
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to count number of values in a range in a given vector.
Next: Wrtie a R program to create a vector and find the length and the dimension of the vector.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework