可以根据输入对象名称创建自己命名的列表吗? [英] 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屋!
查看全文