如何选择一列的最大总和,而另一列的总和小于 R 中的常量?
How do I choose the max sum of one column while the sum of another column is less than constant in R?
假设我有一个包含 2 列 x 和 y 的数据框。
如何从 x 中选择 3 个元素,使其总和最大,而 y 的总和保持在一定数量以下。
x y
1 50 5
2 25 6
3 35 3
4 45 7
5 12 9
例如我希望 y 的总和 <= 20 并且 x 的总和尽可能大。那么 x 中 3 个元素的最大总和将是条目 1、3、4 (50+35+45)。我可以使用什么函数来执行此操作?
您可以使用 combn()
获取 3 行的所有可能组合,然后测试每组行:
df <- data.frame(
x = c(50, 25, 35, 45, 12),
y = c(5, 6, 3, 7, 9)
)
rowsets <- combn(1:nrow(df), m = 3, simplify = FALSE)
x_sums <- vector("double", length = length(rowsets))
for (i in seq_along(rowsets)) {
df_rows <- df[rowsets[[i]], ]
x_sums[[i]] <- if (sum(df_rows$y) <= 20) sum(df_rows$x) else NA_real_
}
df[rowsets[[which.max(x_sums)]], ]
#> x y
#> 1 50 5
#> 3 35 3
#> 4 45 7
由 reprex package (v2.0.1)
创建于 2022-03-01
假设我有一个包含 2 列 x 和 y 的数据框。
如何从 x 中选择 3 个元素,使其总和最大,而 y 的总和保持在一定数量以下。
x y
1 50 5
2 25 6
3 35 3
4 45 7
5 12 9
例如我希望 y 的总和 <= 20 并且 x 的总和尽可能大。那么 x 中 3 个元素的最大总和将是条目 1、3、4 (50+35+45)。我可以使用什么函数来执行此操作?
您可以使用 combn()
获取 3 行的所有可能组合,然后测试每组行:
df <- data.frame(
x = c(50, 25, 35, 45, 12),
y = c(5, 6, 3, 7, 9)
)
rowsets <- combn(1:nrow(df), m = 3, simplify = FALSE)
x_sums <- vector("double", length = length(rowsets))
for (i in seq_along(rowsets)) {
df_rows <- df[rowsets[[i]], ]
x_sums[[i]] <- if (sum(df_rows$y) <= 20) sum(df_rows$x) else NA_real_
}
df[rowsets[[which.max(x_sums)]], ]
#> x y
#> 1 50 5
#> 3 35 3
#> 4 45 7
由 reprex package (v2.0.1)
创建于 2022-03-01