Home > database >  Append an element to each atomic vector in a list in R
Append an element to each atomic vector in a list in R

Time:11-28

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.

CodePudding user response:

With Map append:

Map(append, my_list, elements)

# [[1]]
# [1] "apple"  "pear"   "banana"
# 
# [[2]]
# [1] "carrot"    "turnip"    "aubergine"
  • Related