我想設置一個列表,其中的值保持未初始化(我計劃稍後添加內容)。人們通常如何做到這一點?我已經做了:如何用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