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

How to convert two columns of a data frame to a named vector

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

setNames(object = nm, nm) 

Where an object for which a names attribute will be meaningful. And nm is a character vector of names to assign to the object.

How to convert two columns of a data frame to a named vector in the R program

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

ALGORITHM

STEP 1: Assign variables Dataf with data frame

STEP 2: First print 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 holding 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)
print(result)
                                      

OUTPUT

[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"