Запустите combn
, преобразуйте это в data.frame и затем Filter
из желаемых столбцов.Он состоит из одной строки и не имеет подписки.
target4 <- function(x, target = 0) {
Filter(function(x) sum(x) == target, as.data.frame(combn(x, 4)))
}
TestVector <- c(1, 0, -1, 0, -2, 2)
target4(TestVector)
, что дает:
V1 V9 V14
1 1 1 0
2 0 -1 0
3 -1 -2 -2
4 0 2 2
2) Дольше, но не использует combn
.
target4a <- function(x, target = 0) {
g <- do.call("expand.grid", rep(list(seq_along(x)), 4))
ok <- apply(g, 1, function(x) all(diff(x) > 0))
g2 <- apply(g[ok, ], 1, function(ix) x[ix])
g2[, colSums(g2) == target]
}
target4a(TestVector)
3) или, возможно, разбить (2) на пользовательские комбинации и (1).
combn4 <- function(x) {
g <- do.call("expand.grid", rep(list(seq_along(x)), 4))
ok <- apply(g, 1, function(x) all(diff(x) > 0))
apply(g[ok, ], 1, function(ix) x[ix])
}
target4b <- function(x, target = 0) {
Filter(function(x) sum(x) == target, as.data.frame(combn4(x)))
}
target4b(TestVector)