2014-01-20 65 views
2

我有矢量列表,並且想要將矢量指定給它的一個位置(覆蓋)。以下是示例代碼:R - 替換矢量列表中的元素

for (nodeId in names(chains)) { 
    chains[nodeId] <- unlist(chains[nodeId])[-1] 
} 

分配後我收到許多警告,告訴我列表長度不相等。我明白,發生的任務不是我想要的。

有什麼辦法可以用unlist(chains[nodeId])[-1]代替chains[nodeId]中的元素嗎?

當我做str(chains)str(chains[nodeId])str(unlist(chains[nodeId])[-1])我獲得以下的輸出:

$str(chains) 
List of 15 
$ 4 : chr [1:3] "root" "alcohol< 9.85" "totalSulfurDioxide>=60.5" 
$ 10 : chr [1:4] "root" "alcohol< 9.85" "totalSulfurDioxide< 60.5" "sulphates< 0.575" 
$ 22 : chr [1:5] "root" "alcohol< 9.85" "totalSulfurDioxide< 60.5" "sulphates>=0.575" ... 
(...) lots more 

$str(chains[nodeId]) 
List of 1 
$ 4: chr [1:3] "root" "alcohol< 9.85" "totalSulfurDioxide>=60.5" 

$str(unlist(chains[nodeId])[-1]) 
Named chr [1:2] "alcohol< 9.85" "totalSulfurDioxide>=60.5" 
- attr(*, "names")= chr [1:2] "42" "43" 

更新:str替換dput;加入dput(chains[nodeId])

$ dput(chains) 
structure(list(`4` = "alcohol< 9.85", `10` = "alcohol< 9.85", 
    `22` = "alcohol< 9.85", `92` = "alcohol< 9.85", `93` = "alcohol< 9.85", 
    `47` = "alcohol< 9.85", `24` = "alcohol>=9.85", `50` = "alcohol>=9.85", 
    `102` = "alcohol>=9.85", `103` = "alcohol>=9.85", `26` = "alcohol>=9.85", 
    `27` = "alcohol>=9.85", `28` = "alcohol>=9.85", `29` = "alcohol>=9.85", 
    `15` = c("root", "alcohol>=9.85", "alcohol>=11.55", "sulphates>=0.685" 
    )), .Names = c("4", "10", "22", "92", "93", "47", "24", "50", 
"102", "103", "26", "27", "28", "29", "15")) 

$ dput(chains[nodeId]) 
structure(list(`15` = c("root", "alcohol>=9.85", "alcohol>=11.55", 
"sulphates>=0.685")), .Names = "15") 

$ dput(unlist(chains[nodeId])[-1)) 
structure(c("alcohol>=9.85", "alcohol>=11.55", "sulphates>=0.685" 
), .Names = c("152", "153", "154")) 

$ dput(chains[nodeId]) 
structure(list(`15` = "alcohol>=9.85"), .Names = "15") 

我想實現的是從向量中刪除第一個元素鎖鏈[NODEID]

+2

你可以讓你的問題重現嗎?什麼是輸出(組成一些,或使用'dput'),期望的結果是什麼?你使用哪些代碼無效(你或多或少提供了這些代碼)? –

+0

你到底想做什麼?你能舉一個例子,說明手術前後列表的樣子嗎? –

回答

3

如果chains是列表,nodeId是一個字符串,然後chains[nodeId]將名單長一個。您需要chains[[nodeId]],其中包含該列表的內容。

+0

謝謝!這是我不知道的雙括號。 –

2

這是你想要的嗎?

# make a list of vectors since no data provided 
origlist<-lapply(1:3,function(x)c("a",paste0("b",x),"c")) 
names(origlist)<-c("_1","_2","_3") 

$`_1` 
[1] "a" "b1" "c" 

$`_2` 
[1] "a" "b2" "c" 

$`_3` 
[1] "a" "b3" "c" 

# remove first item from each as per your example 
lapply(origlist, tail, n = -1) 

$`_1` 
[1] "b1" "c" 

$`_2` 
[1] "b2" "c" 

$`_3` 
[1] "b3" "c" 
+0

感謝您的回答,我花了一段時間才明白這一點,但這真的很有趣。我會接受裏奇的回答,因爲這正是我所期待的。 –