2014-03-04 37 views
1

假設矢量的隨後的列表,清單data.table

ll <- structure(list(
    `007` = NULL, `1908` = 2L, `1934` = NULL, `1948` = NULL, `333` = 4L, baloni = 17L, abate = 19L, abatjour = 18L, abbacchio = 20:32, abbeveraggio = 33L), 
    .Names = c("007", "1908", "1934", "1948", "333", "abaloni", "abate", "abatjour", "abbacchio", "abbeveraggio" 
)) 

其中它們中的每一個表示設定位置(即,索引)的。

什麼是創建data.table的快速而智能的方法,其中每行都包含相應位置所屬列表的名稱?

所以,以前的對象ll結果會是以下幾點:

   V1 
1:   NA 
2:   1908 
3:   NA 
4:   333 
5:   NA 
6:   NA 
7:   NA 
8:   NA 
9:   NA 
10:   NA 
11:   NA 
12:   NA 
13:   NA 
14:   NA 
15:   NA 
16:   NA 
17:  abaloni 
18:  abatjour 
19:  abate 
20: abbacchio 
21: abbacchio 
22: abbacchio 
23: abbacchio 
24: abbacchio 
25: abbacchio 
26: abbacchio 
27: abbacchio 
28: abbacchio 
29: abbacchio 
30: abbacchio 
31: abbacchio 
32: abbacchio 
33: abbeveraggio 

一些注意事項:

  • 名單孩子不具有相同的長度,不存在有
  • 位置待填寫NA

我認爲解決方案主要包括恢復列表的結構(索引與條款),但當時我無法達成解決方案。

一些幫助或建議?

謝謝。

回答

1

這裏有一個辦法:

# create matirx 
mat <- do.call(rbind, lapply(seq_along(ll), function(x) 
    if (!is.null(ll[[x]]))cbind(ll[[x]], names(ll)[x]))) 

# create index 
idx <- as.integer(mat[, 1]) 

# create vector 
vec <- rep(NA_character_, max(idx)) 
vec[idx] <- mat[, 2] 

# create data.table 
library(data.table) 
data.table(V1 = vec) 

結果:

   V1 
1:   NA 
2:   1908 
3:   NA 
4:   333 
5:   NA 
6:   NA 
7:   NA 
8:   NA 
9:   NA 
10:   NA 
11:   NA 
12:   NA 
13:   NA 
14:   NA 
15:   NA 
16:   NA 
17:  abaloni 
18:  abatjour 
19:  abate 
20: abbacchio 
21: abbacchio 
22: abbacchio 
23: abbacchio 
24: abbacchio 
25: abbacchio 
26: abbacchio 
27: abbacchio 
28: abbacchio 
29: abbacchio 
30: abbacchio 
31: abbacchio 
32: abbacchio 
33: abbeveraggio 
       V1 
1

我只是通過你的列表循環和使用set

d = data.table(rep(NA_character_, max(sapply(ll, max)))) 

for (i in seq_along(ll)) 
    if (!is.null(ll[[i]])) set(d, ll[[i]], 1L, names(ll)[i])