2

I have 3 different vectors, and i would like to combine then into a list of vectors. But i would like to maintain the names of the vectors in the lists names. Below is the way i've been doing it.

A<-seq(from=1, to=10, by=1)
B<-rep(11,10)
C<-seq(from=50, to=100, by=10)

ABC<-list(A,B,C)

This is the part i would like streamlined

names(ABC)<-c("A", "B", "C")

Thank you.

MadmanLee
  • 478
  • 1
  • 5
  • 18
  • 6
    ẁhat about `list(A=A,B=B,C=C)` ? – agstudy Apr 03 '17 at 23:08
  • HAHA, thanks.. little embaressed now. – MadmanLee Apr 03 '17 at 23:10
  • 4
    Also `mget(c("A","B","C"))` – thelatemail Apr 03 '17 at 23:13
  • 1
    If you're doing this frequently, I suppose you could define a utility function for it, like: ```named_list <- function(...) `names<-`(list(...), as.character(substitute(list(...))[-1]))``` Then it's just `named_list(A, B, C)` – Tim Goodman Apr 03 '17 at 23:38
  • Probably not worth it unless you have something more like: `list(A=A,B=B,C=C,D=D,E=E,F=F,G=G,H=H,...,Z=Z)` :) – Tim Goodman Apr 03 '17 at 23:44
  • 3
    If you happen to have tibble/tidyverse loaded anyway, `tibble::lst(A, B, C)` will automatically set names. – alistaire Apr 03 '17 at 23:44
  • Inspired by the output of `dput`: `ABC <- structure(list(A, B, C), names = c("A", "B", "C"))` – mt1022 Apr 04 '17 at 01:16
  • @TimGoodman This is more of what i am looking for. Still a bit confused on when to use substitute vs. quote. – MadmanLee Apr 04 '17 at 01:51
  • 1
    @MadmanLee A key difference it that if the input to `substitute` contains formal parameters for the function you're in, it will replace them with the actual (unevaluated) arguments from outside the function. So in my comment above, `substitute(list(...))` returned the call `list(A, B, C)`, whereas `quote(list(...))` would have returned the call `list(...)`. – Tim Goodman Apr 04 '17 at 17:29

1 Answers1

0

Alrighty, using @TimGoodman 's suggestion i created a function that does this for me. Wishing list had this as an optional function.

named.list<-function(...){
    bob<-list(...)
    names(bob)<-as.character(substitute((...)))[-1]
    return(bob)
}

Thank you!

MadmanLee
  • 478
  • 1
  • 5
  • 18