簡體   English   中英

如何在列表中間插入一個元素?

[英]How to insert an element in the middle of a list?

我有一個包含多個元素的列表,比如 10。

testList <- split(1:10,1:10)

如何在列表中間插入一個新元素,比如位置 3?

循環遍歷所有元素的蠻力方式將起作用,但只是想知道是否有更優雅的方式來做到這一點?

我認為append函數就是你要找的:

append(testList, list(x=42), 3)
$`1`
[1] 1

$`2`
[1] 2

$`3`
[1] 3

$x
[1] 42

$`4`
[1] 4
#snipped....

對於更復雜的列表,您可能會發現 utils 包中的modifyList函數很有用。 它允許有針對性的修改。 什么是支持是在數據幀的行插入。

使用提取指數:

> testList[5:11] <- c('something', testList[5:10])
> str(testList)
List of 11
 $ 1 : int 1
 $ 2 : int 2
 $ 3 : int 3
 $ 4 : int 4
 $ 5 : chr "something"
 $ 6 : int 5
 $ 7 : int 6
 $ 8 : int 7
 $ 9 : int 8
 $ 10: int 9
 $   : int 10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM