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:")
result = setNames(as.character(df$name), df$code)

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?

Follow us on Facebook and Twitter for latest update.