Converting two columns of a data frame to a named vector
24,357
Solution 1
Use the names
function:
whatyouwant <- as.character(dd$name)
names(whatyouwant) <- dd$crit
as.character
is necessary, because data.frame
and read.table
turn characters into factors with default settings.
If you want a one-liner:
whatyouwant <- setNames(as.character(dd$name), dd$crit)
Solution 2
You can also use deframe(x)
from the tibble package for this.
tibble::deframe()
It converts the first column to names and second column to values.
Solution 3
You can make a vector from dd$name
, and add names using names()
, but you can do it all in one step with structure()
:
whatiwant <- structure(as.character(dd$name), names = as.character(dd$crit))
Solution 4
Here is a very general, easy, tidy way:
library(dplyr)
iris %>%
pull(Sepal.Length, Species)
The first argument is the values, the second argument is the names.
Solution 5
For variety, try split
and unlist
:
unlist(split(as.character(dd$name), dd$crit))
# a b c d
# "Alpha" "Beta" "Caesar" "Doris"
Related videos on Youtube
Author by
Stefan F
Updated on January 27, 2021Comments
-
Stefan F over 3 years
I need to convert a multi-row two-column
data.frame
to a named character vector. Mydata.frame
would be something like:dd = data.frame(crit = c("a","b","c","d"), name = c("Alpha", "Beta", "Caesar", "Doris") )
and what I actually need would be:
whatiwant = c("a" = "Alpha", "b" = "Beta", "c" = "Caesar", "d" = "Doris")
-
Roland over 10 yearsIt should be pointed out that this makes duplicated names unique by appending a number to them. It's also not very efficient with big vectors.
-
HowYaDoing over 4 yearsThank you John! I am amazed that after years of using the tidyverse I still learn about functions that are so useful. I wish I knew about this a long time ago. I guess I'm always a student.
-
merv almost 4 yearsVery neat. Probably will become my goto once it goes live.
-
ChrKoenig over 2 yearsshould be the top answer in 2021
-
acvill over 2 yearsFor anyone coming to this post asking the inverse question - How do I convert a named vector to a two-column data frame? - the answer is
tibble::enframe()