我有以下資料,顯示了 5 個可能被邀請參加派對的孩子以及他們居住的社區。
我也有一個解決方案串列(是否邀請孩子的二進制指標;例如,第一個解決方案邀請凱利、吉娜和帕蒂。
data <- data.frame(c("Kelly", "Andrew", "Josh", "Gina", "Patty"), c(1, 1, 0, 1, 0), c(0, 1, 1, 1, 0))
names(data) <- c("Kid", "Neighborhood A", "Neighborhood B")
solutions <- list(c(1, 0, 0, 1, 1), c(0, 0, 0, 1, 1), c(0, 1, 0, 1, 1), c(1, 0, 1, 0, 1), c(0, 1, 0, 0, 1))
我正在尋找一種現在通過以下方式過濾解決方案的方法:
a) 只保留社區 A 和社區 B 至少有 3 個孩子的解決方案(如果兩個孩子都屬于,一個孩子可以算作兩個孩子)
b) 只保留選擇了至少 3 個孩子的解決方案(即總和 >= 3)
我認為我需要以某種方式將資料加入解決方案中的解決方案,但是由于解決方案卡在串列中,因此我對如何操作所有內容有點迷茫。基本上是在尋找一種方法來向串列中的每個解決方案添加條目,指示 a)解決方案有多少孩子,b)有多少來自社區 A 的孩子,以及 c)有多少來自社區 B 的孩子。從那里我必須以某種方式過濾串列以僅保留滿足> = 3的解決方案?
先感謝您!
uj5u.com熱心網友回復:
我寫了一個小函式來檢查每個解決方案并根據您的要求回傳TRUE或回傳。FALSE將您傳遞solutions給此 usingsapply()將為您提供一個邏輯向量,您可以使用該向量進行子集solutions化以僅保留滿足要求的那些。
check_solution <- function(solution, data) {
data <- data[as.logical(solution),]
sum(data[["Neighborhood A"]]) >= 3 && sum(data[["Neighborhood B"]]) >= 3
}
### No need for function to test whether `sum(solution) >= 3`, since
### this will *always* be true if either neighborhood sums is >= 3.
tests <- sapply(solutions, check_solution, data = data)
# FALSE FALSE FALSE FALSE FALSE
solutions[tests]
# list()
### none of the `solutions` provided actually meet criteria
編輯: OP 在評論中詢問如何針對資料中的所有社區進行測驗,并回傳TRUE指定數量的社區是否有足夠的孩子。下面是一個使用dplyr.
library(dplyr)
data <- data.frame(
c("Kelly", "Andrew", "Josh", "Gina", "Patty"),
c(1, 1, 0, 1, 0),
c(0, 1, 1, 1, 0),
c(1, 1, 1, 0, 1),
c(0, 1, 1, 1, 1)
)
names(data) <- c("Kid", "Neighborhood A", "Neighborhood B", "Neighborhood C",
"Neighborhood D")
solutions <- list(c(1, 0, 0, 1, 1), c(0, 0, 0, 1, 1), c(0, 1, 0, 1, 1),
c(1, 0, 1, 0, 1), c(0, 1, 0, 0, 1))
check_solution <- function(solution,
data,
min_kids = 3,
min_neighborhoods = NULL) {
neighborhood_tests <- data %>%
filter(as.logical(solution)) %>%
summarize(across(starts_with("Neighborhood"), ~ sum(.x) >= min_kids)) %>%
as.logical()
# require all neighborhoods by default
if (is.null(min_neighborhoods)) min_neighborhoods <- length(neighborhood_tests)
sum(neighborhood_tests) >= min_neighborhoods
}
tests1 <- sapply(solutions, check_solution, data = data)
solutions[tests1]
# list()
tests2 <- sapply(
solutions,
check_solution,
data = data,
min_kids = 2,
min_neighborhoods = 3
)
solutions[tests2]
# [[1]]
# [1] 1 0 0 1 1
#
# [[2]]
# [1] 0 1 0 1 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/439342.html
