Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R list from variables using variable names [duplicate]

Tags:

r

I've looked extensively for a solution for this very simple task and though I have a solution, it seems like there must be a better way. The task is to create a list from a set of variables, using the variable names as names for each element in the list, e.g.:

a <- 2
b <- 'foo'
c <- 1:4

My current solution:

named.list <- function(...) { 
    l <- list(...)
    names(l) <- sapply(substitute(list(...)), deparse)[-1]
    l 
}
named.list(a,b,c)

Produces:

$a
[1] 2

$b
[1] "foo"

$c
[1] 1 2 3 4
like image 864
waferthin Avatar asked Jul 24 '13 10:07

waferthin


2 Answers

A couple of ways I can think of include mget (make assumptions about the environment your objects are located in):

mget( c("a","b","c") )
$a
[1] 2

$b
[1] "foo"

$c
[1] 1 2 3 4

Or as an edit to your function, you could use, match.call like this:

named.list <- function(...) { 
    l <- list(...)
    names(l) <- as.character( match.call()[-1] )
   l
}
named.list( a,b,c)
$a
[1] 2

$b
[1] "foo"

$c
[1] 1 2 3 4

Or you can do it in one go using setNames like this:

named.list <- function(...) { 
    l <- setNames( list(...) , as.character( match.call()[-1]) ) 
    l
}

named.list( a,b,c)
$a
[1] 2

$b
[1] "foo"

$c
[1] 1 2 3 4
like image 133
Simon O'Hanlon Avatar answered Nov 02 '22 21:11

Simon O'Hanlon


If you already using tidyverse packages, then you might be interested in using the tibble::lst function which does this

tibble::lst(a, b, c)
# $a
#  [1] 2
#  
# $b
# [1] "foo"
# 
# $c
# [1] 1 2 3 4
like image 34
MrFlick Avatar answered Nov 02 '22 22:11

MrFlick