I have a nested list l3 as:
l1<- as.list(c(1,2,3,4,5))
l1
l2<- as.list(c(6,7,8,9,10))
l2
l3<- list(l1,l2)
l3
l3 shows as:
> l3
[[1]]
[[1]][[1]]
[1] 1
[[1]][[2]]
[1] 2
[[1]][[3]]
[1] 3
[[1]][[4]]
[1] 4
[[1]][[5]]
[1] 5
[[2]]
[[2]][[1]]
[1] 6
[[2]][[2]]
[1] 7
[[2]][[3]]
[1] 8
[[2]][[4]]
[1] 9
[[2]][[5]]
[1] 10
I need to add a third list l4 to l3 such that l3 becomes:
[[1]][[1]]
[1] 1
to
[[2]][[5]]
[1] 10
[[3]][[1]]
[1] 30
[[3]][[2]]
[1] 32
[[3]][[3]]
[1] 33
[[3]][[4]]
[1] 34
[[3]][[5]]
[1] 35
where l4 was:
l4<- as.list(c(31,32,33,34,35))
how do I accomplish it? I've tried (c)
, list
, even explicitly put the arguments and got an out of bounds error
. What can I use to get this done?
To add new values to the end of the nested list, use append() method. When you want to insert an item at a specific position in a nested list, use insert() method. You can merge one list into another by using extend() method. If you know the index of the item you want, you can use pop() method.
To add or append an element to the list in R use append() function. This function takes 3 parameters input list, the string or list you wanted to append, and position. The list. append() function from the rlist package can also use to append one list with another in R.
Almost all data in R is stored in a vector, or even a vector of vectors. A list is a recursive vector: a vector that can contain another vector or list in each of its elements. Lists are one of the most flexible data structures in R.
It works with append
and list
:
append(l3, list(l4))
The result:
> str(append(l3, list(l4)))
List of 3
$ :List of 5
..$ : num 1
..$ : num 2
..$ : num 3
..$ : num 4
..$ : num 5
$ :List of 5
..$ : num 6
..$ : num 7
..$ : num 8
..$ : num 9
..$ : num 10
$ :List of 5
..$ : num 31
..$ : num 32
..$ : num 33
..$ : num 34
..$ : num 35
I don't know what you have tried with c
, but it works
c(l3,list(l4))
PS: append
is a wrapper of c
to insert in a specific index, (see after argument )
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