【问题标题】:handling sequential tasks with purrr用 purrr 处理顺序任务
【发布时间】:2019-11-29 17:41:21
【问题描述】:

我想获取对象列表并从所有对象中构建一个对象。实际用例是将多个 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"

【问题讨论】:

    标签: r purrr seurat


    【解决方案1】:
    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"
    

    【讨论】:

    • 这很好,实际上它指示我减少,这更好。我选择了 list(w1, w2, w3, w4) %>% reduce(function(x,y) ifelse(nchar(x)==0,y$b,paste0(x," ",y$b)) ,.init = '') 谢谢瑞恩。我会尽可能接受答案。
    【解决方案2】:

    在基础 R 中使用 do.calllapply

    do.call(paste, lapply(list(w1,w2,w3,w4), `[[`, "b"))
    
    # [1] "This is the desired results"
    

    【讨论】:

      【解决方案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))
      

      【讨论】:

      • 谢谢弗利克先生。 reduce 是我需要的功能。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多