可以创建基于输入对象名称来命名自己的列表吗? [英] Can lists be created that name themselves based on input object names?
本文介绍了可以创建基于输入对象名称来命名自己的列表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
能够创建一个R列表对象而不必指定每个元素的名称对我非常有帮助.例如:
It would be very helpful to me to be able to create an R list object without having to specify the names of each element. For example:
a1 <- 1
a2 <- 20
a3 <- 1:20
b <- list(a1,a2,a3, inherit.name=TRUE)
> b
[[a1]]
[1] 1
[[a2]]
[1] 20
[[a3]]
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
这将是理想的.有什么建议吗?
This would be ideal. Any suggestions?
推荐答案
巧合的是,我刚刚编写了此函数.看起来很像@joran的解决方案,但是它尝试不踩踏已经命名的参数.
Coincidentally, I just wrote this function. It looks a lot like @joran's solution, but it tries not to stomp on already-named arguments.
namedList <- function(...) {
L <- list(...)
snm <- sapply(substitute(list(...)),deparse)[-1]
if (is.null(nm <- names(L))) nm <- snm
if (any(nonames <- nm=="")) nm[nonames] <- snm[nonames]
setNames(L,nm)
}
## TESTING:
a <- b <- c <- 1
namedList(a,b,c)
namedList(a,b,d=c)
namedList(e=a,f=b,d=c)
从评论中复制:如果您想要CRAN软件包中的某些内容,可以使用Hmisc::llist
:
Copied from comments: if you want something from a CRAN package, you can use Hmisc::llist
:
Hmisc::llist(a, b, c, d=a, labels = FALSE)
唯一明显的区别是,在这种情况下,各个向量也都具有名称.
The only apparent difference is that the individual vectors also have names in this case.
这篇关于可以创建基于输入对象名称来命名自己的列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文