【问题标题】:Create list from two vectors with every combo of each从两个向量创建列表,每个向量的每个组合
【发布时间】:2019-08-15 19:19:50
【问题描述】:

假设我有两个向量(在下面的例子中,它们是 cyclesthedates),我想将它们之间的每对组合组合到一个列表中。下面的代码为我提供了我想要的输出inlist,但我认为它不是很有效。我用outer 尝试了不同的东西,但我无法成功。

library(lubridate)
library(data.table)
cycles <- c(1,2,10*1:24)
thedates <- seq(ymd('2016-08-13',tz='GMT'), ymd('2019-08-13',tz='GMT'),by='day')

inputs <- matrix(nrow=length(thedates)*length(cycles),ncol=2)
inputs[,1]  <- rep(thedates,each=length(cycles))
inputs[,2] <- rep(cycles,length(thedates))
inlist <- lapply(1:nrow(inputs), function(x) c(inputs[x,1], inputs[x,2]))

【问题讨论】:

  • tidyr 包中的 crossing 函数怎么样? stackoverflow.com/questions/43228379/…
  • 考虑一下来自 tinyverse 的 expand.gridbase,包。
  • 仅供参考 - 如果您尝试使用 google 连接类型,这将被视为交叉或笛卡尔连接。

标签: r


【解决方案1】:

由于你有data.table作为一个包,你可以使用CJ()交叉连接功能:

CJ(cycles, thedates)

会比expand.grid快很多:

expand.grid(cycles, thedates)

我还认为拥有一堆列表没有帮助,但您可以将其拆分为 @Reeza 提供的以匹配您的输出。

【讨论】:

    【解决方案2】:

    这似乎对我有用,但不确定它是否更有效。

    z = split(crossing(cycles, thedates), seq(length(cycles) * length(thedates)))
    

    你会得到一个每两个列表的列表。如果您想要一个 tibble 或数据框,请删除该代码的 split 部分,但由于您正在使用列表,我认为这是您需要的。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    相关资源
    最近更新 更多