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

R – Combine two elements within the SAME list. Preferentially a purrr solution

I am looking for a purrr solution for the following problem:

Say, we have some list:

    list(     c("Hello",      "Well",   "You"  ),
              c("again",      "done,",  "annoy"),
              c("my friend!", "boy!",   "me!"  )      )

Now, I would like to to combine the the first two elements within that list.

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

My desired output is:

    list(     c("Hello",      "Well",   "You"  , "again",      
               "done,",  "annoy"),
              c("again",      "done,",  "annoy"),
              c("my friend!", "boy!",   "me!"  )      )

Appreciate your help! Thanks.

>Solution :

Subset the first two list elements, concatenate with do.call and
assign (<-) it back to the first element

lst1[[1]] <- do.call(c, lst1[1:2])

-output

> lst1
[[1]]
[1] "Hello" "Well"  "You"   "again" "done," "annoy"

[[2]]
[1] "again" "done," "annoy"

[[3]]
[1] "my friend!" "boy!"       "me!"       

With purrr, we can use modify_in

library(purrr)
modify_in(lst1, 1, ~ flatten_chr(lst1[1:2]))
[[1]]
[1] "Hello" "Well"  "You"   "again" "done," "annoy"

[[2]]
[1] "again" "done," "annoy"

[[3]]
[1] "my friend!" "boy!"       "me!"      

data

lst1 <- list(c("Hello", "Well", "You"), c("again", "done,", "annoy"), 
    c("my friend!", "boy!", "me!"))
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