R - 合并 SAME 列表中的两个元素。优先选择 purrr 解决方案
R - Combine two elements within the SAME list. Preferentially a purrr solution
我正在为以下问题寻找 purrr 解决方案:
说,我们有一些列表:
list( c("Hello", "Well", "You" ),
c("again", "done,", "annoy"),
c("my friend!", "boy!", "me!" ) )
现在,我想合并该列表中的前两个元素。
我想要的输出是:
list( c("Hello", "Well", "You" , "again",
"done,", "annoy"),
c("again", "done,", "annoy"),
c("my friend!", "boy!", "me!" ) )
感谢您的帮助!谢谢
子集前两个 list
元素,c
与 do.call
连接并
将 (<-
) 分配回第一个元素
lst1[[1]] <- do.call(c, lst1[1:2])
-输出
> lst1
[[1]]
[1] "Hello" "Well" "You" "again" "done," "annoy"
[[2]]
[1] "again" "done," "annoy"
[[3]]
[1] "my friend!" "boy!" "me!"
有了purrr
,我们可以用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!"
数据
lst1 <- list(c("Hello", "Well", "You"), c("again", "done,", "annoy"),
c("my friend!", "boy!", "me!"))
我认为您不需要 purrr
解决方案,但如果您出于某些工作流程原因坚持...
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))
但我只想做...
x[[1]] <- c(x[[1]], x[[2]])
我正在为以下问题寻找 purrr 解决方案:
说,我们有一些列表:
list( c("Hello", "Well", "You" ),
c("again", "done,", "annoy"),
c("my friend!", "boy!", "me!" ) )
现在,我想合并该列表中的前两个元素。
我想要的输出是:
list( c("Hello", "Well", "You" , "again",
"done,", "annoy"),
c("again", "done,", "annoy"),
c("my friend!", "boy!", "me!" ) )
感谢您的帮助!谢谢
子集前两个 list
元素,c
与 do.call
连接并
将 (<-
) 分配回第一个元素
lst1[[1]] <- do.call(c, lst1[1:2])
-输出
> lst1
[[1]]
[1] "Hello" "Well" "You" "again" "done," "annoy"
[[2]]
[1] "again" "done," "annoy"
[[3]]
[1] "my friend!" "boy!" "me!"
有了purrr
,我们可以用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!"
数据
lst1 <- list(c("Hello", "Well", "You"), c("again", "done,", "annoy"),
c("my friend!", "boy!", "me!"))
我认为您不需要 purrr
解决方案,但如果您出于某些工作流程原因坚持...
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))
但我只想做...
x[[1]] <- c(x[[1]], x[[2]])