我想设置一个列表,其中的值保持未初始化(我计划稍后添加内容)。人们通常如何做到这一点?我已经做了:如何用R/Splus中的名称创建一个没有条目的列表?
mylist.names <- c("a", "b", "c")
mylist <- as.list(rep(NA, length(mylist.names)))
names(mylist) <- mylist.names
但这看起来很有点哈克。必须有一个更标准的方法来做到这一点...对吗?
我想设置一个列表,其中的值保持未初始化(我计划稍后添加内容)。人们通常如何做到这一点?我已经做了:如何用R/Splus中的名称创建一个没有条目的列表?
mylist.names <- c("a", "b", "c")
mylist <- as.list(rep(NA, length(mylist.names)))
names(mylist) <- mylist.names
但这看起来很有点哈克。必须有一个更标准的方法来做到这一点...对吗?
我会做这样的:
mylist.names <- c("a", "b", "c")
mylist <- vector("list", length(mylist.names))
names(mylist) <- mylist.names
一点点短版本比蒂洛:)
mylist <- sapply(mylist.names,function(x) NULL)
我喜欢它。有一件事要补充,如果你的名字是数字,数字值将被忽略为名字,并且只使用1,2,3。为了规避这种情况,请尝试:'sapply(as.character(4:6),function(x)NULL)' – mpettis 2013-09-12 15:28:10
谨防在函数内部使用'sapply' https://twitter.com/hadleywickham/status/434339083871993856 – Jubbles 2016-01-20 01:50:45
可以用mylist <--purrr :: map(mylist.names,〜NULL)替换'sapply'' – psychonomics 2017-04-13 07:07:11
另一个棘手的方式做到这一点:
mylist.names <- c("a", "b", "c")
mylist <- NULL
mylist[mylist.names] <- list(NULL)
该作品因为你替换不存在的条目,所以它们被创建。该列表(NULL)不幸必需的,因为NULL意味着删除条目:
x <- list(a=1:2, b=2:3, c=3:4)
x["a"] <- NULL # removes the "a" entry!
x["c"] <- list(NULL) # assigns NULL to "c" entry
我可能会使用mylist < - list(),因为它更清楚地表明你正在初始化一个空列表。我确实有点惊讶,它将它设置为NULL。我假设当你以这种方式分配时,'mylist'从'NULL'被提升到一个列表。 – 2014-07-03 22:34:42
依稀相关:http://stackoverflow.com/questions/5042806/r-creating-a-named-vector-from-variables/5043280#5043280 – Andrie 2011-04-16 18:37:31