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