2

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..

stevec
  • 41,291
  • 27
  • 223
  • 311

2 Answers2

3

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)
caldwellst
  • 5,719
  • 6
  • 22
1

You can use :

library(dplyr)
iris %>%  arrange(Sepal.Length) %>% pull(Sepal.Length) %>%
  setNames(iris %>% arrange(Sepal.Length) %>% pull(Species))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213