2016-01-21 86 views
0

我有一個有名的矢量定義了一些顏色。R - 創建數字列表

my_colors = c("C_T" = "salmon", "C_G" = "gold", "C_A" = "mediumseagreen", "T_G" = "lightseagreen", "T_C" = "royalblue1", "T_A" = "orchid1") 

我想創建一個大小爲N的列表,其中每個條目以數字命名幷包含向量my_colors。列表的結構需要適合特定的格式,因爲我將它提供給一些非常嚴格的功能。下面是一些手動生成所需的結果,並展示了必要的結構代碼:

my_list = list("1" = my_colors, "2" = my_colors, "3" = my_colors, "4" = my_colors, "5" = my_colors, "6" = my_colors) 
str(my_list) 

我試圖寫一個循環來填充空單

test_list = list() 
for (i in 1:6) { 
    test_list[i] = my_colors 
} 

但這返回錯誤消息抱怨長度

我也曾嘗試

test_list = list() 
for (i in 1:6) { 
    test_list[[i]] = my_colors 
} 

test_list = list() 
for (i in 1:6) { 
    x = character(i) 
    test_list[x] = my_colors 
} 

但這兩種方法都沒有給我一個與my_list具有相同結構的test_list。我如何重新創建我用來以遞歸方式填充my_list的手動列表生成?

+1

'rep(list(my_colors),N)'? – Frank

+0

嘗試'my_list < - '名稱< - '(rep(list(my_colors),n),1:n)' –

+0

循環中使用'test_list [[i]] = my_colors'的方法似乎很好。 ? – Frank

回答

1

如果你開始這個(即不應該出現的任何錯誤你的努力之一)

test_list = list() 
for (i in 1:6) { 
    test_list[[i]] = my_colors 
} 

...這是唯一缺少的東西是正確的名稱。輕鬆修復:

names(test_list) <- 1:6 

哦。現在我看到@PierreLafortune已經提出了這個建議。如果您添加的.Names屬性之前,你已經用完你會看到這個(可能有用的)結果這兩個對象all.equal

> all.equal(my_list, test_list) 
[1] "names for target but not for current" 

你也必須通過鍵入

dput(my_list) 
dput(test_list) 
看着底層結構

....並注意到「外部」屬性存在差異。