This question already has an answer here:
这个问题已经有了答案:
- Can lists be created that name themselves based on input object names? 3 answers
- 可以根据输入对象名创建名称本身的列表吗?3答案
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
2 个解决方案
#1
14
A couple of ways I can think of include mget
(make assumptions about the environment your objects are located in):
我能想到的包括mget(假设你的对象所在的环境)的几个方法:
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:
或者作为对函数的编辑,可以使用match。像这样:
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:
或者你可以用这样的setNames来做:
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
#2
1
If you already using tidyverse packages, then you might be interested in using the tibble::lst
function which does this
如果您已经使用了tidyverse包,那么您可能会对使用tibble::lst函数感兴趣
tibble::lst(a, b, c)
# $a
# [1] 2
#
# $b
# [1] "foo"
#
# $c
# [1] 1 2 3 4
#1
14
A couple of ways I can think of include mget
(make assumptions about the environment your objects are located in):
我能想到的包括mget(假设你的对象所在的环境)的几个方法:
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:
或者作为对函数的编辑,可以使用match。像这样:
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:
或者你可以用这样的setNames来做:
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
#2
1
If you already using tidyverse packages, then you might be interested in using the tibble::lst
function which does this
如果您已经使用了tidyverse包,那么您可能会对使用tibble::lst函数感兴趣
tibble::lst(a, b, c)
# $a
# [1] 2
#
# $b
# [1] "foo"
#
# $c
# [1] 1 2 3 4