有条件地循环数据帧的行

Looping over rows of a dataframe conditionally

我下面的循环结构效果很好。但是,如果我们有: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

据我所知,在替代情况下 return 相同输入所需的代码更改最少是将 inputm 包装在函数 list() 以便它们都是长度为 1 的列表,其中单个元素是数据框。数据框本身就是列表(数据框的每一列都是列表的一个元素)。因此,如果您不将数据框包装在 list() 中,lapply 语句将尝试遍历数据框的列并失败。

m <- data.frame(po = c(1,2,1,2), ou = rep(1,4))

input <- rev(expand.grid(ou = seq_len(max(m2$ou)), po = seq_len(max(m2$po))))

lapply(list(input), function(inp) Map(function(p, o)  ## How should this change?
  do.call(rbind, lapply(list(m), function(m1)
    m1[m1$po == p & m1$ou == o, , drop = FALSE])), inp$po, inp$ou))