如何在列表中间插入一个元素? [英] How to insert an element in the middle of a list?

查看:14
本文介绍了如何在列表中间插入一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含几个元素的列表,比如 10 个.

I have a list with several elements, say 10.

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

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

How to insert a new element in the middle of the list, say at position 3?

循环遍历所有元素的蛮力方式会起作用,但只是想知道是否有更优雅的方式来做到这一点?

The brute force way of looping through all the elements will work, but just wondering if there is a more elegant way of doing this?

推荐答案

我认为 append-function 就是你要找的:

I think the append-function is what you are looking for:

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

$`2`
[1] 2

$`3`
[1] 3

$x
[1] 42

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

对于更复杂的列表,您可能会发现 utils 包中的 modifyList 函数很有用.它允许有针对性的修改.它支持的是在数据框中插入行.

For more complex lists you might find the modifyList function in the utils package to be of use. It allows targeted modifications. What it does not support is insertions of rows in a dataframe.

这篇关于如何在列表中间插入一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆