【发布时间】:2025-12-27 19:30:11
【问题描述】:
我下面的循环结构效果很好。但是,如果我们有:m = data.frame(po = c(1,2,1,2), ou = rep(1,4)) 和 input = rev(expand.grid(ou = seq_len(max(m$ou)), po = seq_len(max(m$po)))),并且我希望得到与现在相同的输出(即两个元素的列表),
那么,lapply(input, ... 应该如何变化?
m = list(A = data.frame(po = c(1,2,1,2), ou = rep(1,4)))
# if: `m = data.frame(po = c(1,2,1,2), ou = rep(1,4))`
input <- lapply(m, function(i) rev(expand.grid(ou = seq_len(max(i$ou)),
po = seq_len(max(i$po)))))
# if: `input = rev(expand.grid(ou = seq_len(max(m$ou)), po = seq_len(max(m$po))))`
lapply(input, function(inp) Map(function(p, o) ## Then, how should this change?
do.call(rbind, lapply(m, function(m1)
m1[m1$po == p & m1$ou == o, , drop = FALSE])), inp$po, inp$ou))
#==== Current & Desired Output:
#$A
#$A[[1]]
po ou
A.1 1 1
A.3 1 1
#$A[[2]]
po ou
A.2 2 1
A.4 2 1
【问题讨论】:
-
我有点困惑你在问什么。需要您更改 lapply 语句的输入更改是什么?
-
啊哈,在这种情况下,只需将其包装为
lapply(list(input), ...)
标签: r function dataframe loops lapply