【问题标题】:Function mapped to reduce function to concatenate vectors together映射到减少函数以将向量连接在一起的函数
【发布时间】:2018-09-07 08:16:38
【问题描述】:

我正在尝试编写一个函数,该函数将一个函数映射为 reduce 以将向量列表连接到 1 中,其中包含第一个条目和最后一个条目。

例如,

reduce(list(1:10, 11:20, 21:100), r_cat, .init = NULL)

应该返回一个等于

的向量
1:100

这是我目前所拥有的。

r_cat = function(x, y) {
    out <- y[[1]]
    for(i in seq(2, length(y))) {
        out <- x(out, y[[i]])
    }
    out
}

有什么想法吗?

【问题讨论】:

  • unlist 已经做到了。 unlist(list(1:10, 11:20, 21:100))
  • @JilberUrbina 我在我的 r_cat 中尝试了 unlist(x:y) 并且它没有工作..
  • @JilberUrbina 我想通了... c(unlist(x),unlist(y))

标签: r function vector iteration concatenation


【解决方案1】:

无需编写新函数,unlist 解决您的问题:

List <- list(1:10, 11:20, 21:100)
unlist(List)

如果你想使用 R 基础的Reduce,那么你可以使用c

Reduce("c", List)

您也可以将c 从purrr 插入reduce 得到相同的结果

library(purrr)
reduce(List, c)

【讨论】:

  • 我想通了... c(unlist(x),unlist(y))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-09
  • 2011-06-01
  • 2016-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多