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
Where an object for which a names attribute will be meaningful. And nm is a character vector of names to assign to the object.
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).
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