Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Append an element to each atomic vector in a list in R

I would like to add elements to atomic vectors in a list. For example, from the list:

my_list <- list(c("apple", "pear"), c("carrot", "turnip"))

I would like to add elements elements = c("banana","aubergine") such that each element is appended in sequence to the end of the vector:

ny_new_list <- list(c("apple", "pear", "banana"), c("carrot","turnip", "aubergine"))

I have thought of using unlist and then adding each element in the vector elements in position 3,6,9 etc., but this seems unwieldy and you have to manually change the code depending on how long the vectors in my_list are.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With Map + append:

Map(append, my_list, elements)

# [[1]]
# [1] "apple"  "pear"   "banana"
# 
# [[2]]
# [1] "carrot"    "turnip"    "aubergine"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading