R Program to convert two columns of a data frame to a named vector

February 25, 2023, Learn eTutorial

How to convert two columns of a data frame to a named vector using R?

Here we are explaining how to write an R program to change two columns of a data frame to a named vector. Here we are using a built-in function setNames() for this. The setNames() function helps to set the names on an object and returns the object.

The syntax of this function is 

setNames(object = nm, nm) 

  • object for which a name attribute will be meaningful.
  • nm is a character vector of names to assign to the object.

In this R program, we pass the data frame directly to a built-in function. Here we are using the variable Dataf() for holding the data frame which has two columns code and name. Call the function setName() for creating a named vector as setNames(as.character(Dataf $name), Dataf $code). Finally, display the results.


STEP 1: Assign variables Dataf with data frame

STEP 2: Display the original data frame

STEP 3: Call the function setNames as setNames(as.character(Dataf $name), Dataf $code)

STEP 4: Assign variable result with the result of setName function

STEP 5: print the variable result which holds the result 

R Source Code

                                          Dataf = data.frame(code = c("A","B","C","D"), 
               name = c("Apple", "Ball", "Cat", "Duck")
print("Original vector:")
print(Dataf )
result = setNames(as.character(Dataf $name), Dataf $code)


[1] "Original vector:"
   code  name
1    A  Apple
2    B  Ball
3    C  Duck
4    D  Black
     A       B      C      D 
  "Apple" "Ball" "Cat" "Duck"