I have a list with several elements, say 10.
testList <- split(1:10,1:10)
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?
The add() method adds a given element to a set. If the element is already present, it doesn't add any element.
Inserting an element in list at specific index using list. insert() In python list provides a member function insert() i.e. It accepts a position and an element and inserts the element at given position in the list.
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....
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With