Home > Software design >  R - Combine two elements within the SAME list. Preferentially a purrr solution
R - Combine two elements within the SAME list. Preferentially a purrr solution

Time:02-20

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.

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.

CodePudding user response:

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!"))

CodePudding user response:

I don't think you want a purrr solution, but if you insist for some workflow reason...

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

library(purrr)
modify_at(x, 1, ~ c(., x[[2]]))

# which can simplify to...
x %>% 
  modify_at(1, c, .[[2]])

# or with more purrr!!
x %>% 
  modify_at(1, c, pluck(., 2))

But I would just do...

x[[1]] <- c(x[[1]], x[[2]])
  • Related