w3resource

R Programming: Convert two Columns of a DataFrame 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 :

# Create a data frame 'df' with two columns: 'code' and 'name'
df = data.frame(code = c("R", "G", "W", "B"), 
               name = c("Red", "Green", "White", "Black"))

# Print a message indicating the original data frame
print("Original vector:")

# Print the contents of the data frame 'df'
print(df)

# Convert the 'name' column to a character vector and set the 'code' column as names for the vector
result = setNames(as.character(df$name), df$code)

# Print the named vector 'result'
print(result)

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"                         

Explanation:

  • Create a data frame:
    • df = data.frame(code = c("R", "G", "W", "B"), name = c("Red", "Green", "White", "Black"))
      A data frame df is created with two columns: code (containing "R", "G", "W", "B") and name (containing "Red", "Green", "White", "Black").
  • Print the original data frame:
    • print("Original vector:")
      Prints a message indicating that the following output will display the original data frame.
  • Display the data frame:
    • print(df)
      Displays the content of the data frame df.
  • Convert columns to a named vector:
    • result = setNames(as.character(df$name), df$code)
      Converts the name column to a character vector and uses the code column as names for this vector. The result is a named vector where each name corresponds to an element from the name column.
  • Print the named vector:
    • print(result)
      Displays the named vector result with code values as names and name values as the corresponding elements.

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?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/r-programming-exercises/vector/r-programming-vector-exercise-23.php