stevec
stevec

Reputation: 52328

Conveniently extract a named vector from data.frame using dplyr/tidy?

How can we extract a named vector whose names come from one data.frame column and values from another, conveniently, using the pipe? (and without assigning in between)

Here is a very manual approach

vec <- iris %>% 
  arrange(Sepal.Length) %>% 
  pull(Sepal.Length)

names_for_vec <- iris %>% 
  arrange(Sepal.Length) %>% 
  pull(Species)


names(vec) <- names_for_vec 
names(vec)

# Named vector
vec

Ideally, I'd like to achieve the same result in one line

What I've tried

I've tried variations on the top two answers here, as well as another idea of using "names<-"():


iris %>% 
  arrange(desc(Sepal.Length)) %>% 
  pull(Sepal.Length) %>%  
  `names<-`() # But we can't access the Species column as it was 2 pipes back..

Upvotes: 2

Views: 810

Answers (2)

caldwellst
caldwellst

Reputation: 5956

The pull.data.frame method already accepts an argument for naming. I thought this was available previously, but this might be only in dplyr 1.0, in which case you would need to install from the tidyverse\dplyr Github repo.

iris %>%
  arrange(Sepal.Length) %>%
  pull(Sepal.Length, Species)

Upvotes: 4

Ronak Shah
Ronak Shah

Reputation: 389047

You can use :

library(dplyr)
iris %>%  arrange(Sepal.Length) %>% pull(Sepal.Length) %>%
  setNames(iris %>% arrange(Sepal.Length) %>% pull(Species))

Upvotes: 1

Related Questions