使用purrr处理顺序任务

时间:2018-08-14 14:01:39

标签: r purrr

我想获取对象列表并从所有对象中构建一个对象。实际用例是将多个Seurat对象组合成一个对象。目前,我使用for循环,但是,我很好奇是否可以使用purrr :: map。为了使问题更简单,让我们串联一个列表的一部分。尝试不要对结果太可爱,因为我的真正问题是更困难的(更复杂的功能)。

w1 = list(a="first",b="This")
w2 = list(a="second",b="is")
w3 = list(a="third",b="the")
w4 = list(a="fourth",b="desired results")

期望的结果将是“这是期望的结果”。

list(w1,w2,w3,w4) %>% map(paste,.$b," ")

给予

  

[[1]] [1]“此”

     

[[2]] [1]“是”

     

[[3]] [1]““

     

[[4]] [1]“期望的结果”

我想保存上一次迭代的结果并将其作为参数添加到函数中。

基本上,我想用功能替换以下行。

y=NULL;for (x in list(w1,w2,w3,w4)){ y=ifelse(is.null(y),x$b,paste0(y," ",x$b))}
#y
#"This is the desired result"

3 个答案:

答案 0 :(得分:4)

在基础R中具有do.calllapply

do.call(paste, lapply(list(w1,w2,w3,w4), `[[`, "b"))

# [1] "This is the desired results"

答案 1 :(得分:3)

library(purrr)

list(w1, w2, w3, w4) %>% 
  accumulate(~paste(.x, .y[2][[1]]), .init = '') %>% 
  tail(1) %>% 
  substr(2, nchar(.))

# [1] "This is the desired results"

答案 2 :(得分:3)

我建议使用purrr

list(w1,w2,w3,w4) %>% 
  map_chr("b") %>% 
  paste(collapse=" ")

我们可以将字符串传递给map()以返回该命名元素,并且由于我们只期望字符值,因此可以使用map_chr来获取字符值的向量而不是列表。最后,将其通过管道传递到paste(collapse=)即可将其转换为一个字符串。

但是更一般而言,如果您希望逐渐收合,则可以使用reduce

list(w1, w2, w3, w4) %>% 
  map_chr("b") %>%
  reduce(~paste(.x, .y))
相关问题