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

Datadf = data.frame(code = c("A", "B", "C", "D"), 
                    name = c("Apple", "Ball", "Cat", "Duck")
                   )

print("Original data frame:")
## [1] "Original data frame:"
print(Datadf )
##   code  name
## 1    A Apple
## 2    B  Ball
## 3    C   Cat
## 4    D  Duck
print("Dimension of data frame:")
## [1] "Dimension of data frame:"
print(dim(Datadf))
## [1] 4 2
result = setNames(as.character(Datadf $name), Datadf $code)

print("transformed vector:")
## [1] "transformed vector:"
print(result)
##       A       B       C       D 
## "Apple"  "Ball"   "Cat"  "Duck"
print("Dimension of vector:")
## [1] "Dimension of vector:"
print(dim(result))
## NULL