如果向量包含 5 个元素中的 3 个,则返回 dplyr 中该 ID == TRUE 的所有元素

Spa*_*rky 3 r dplyr

我试图让所有包含五个元素 c(2,3,4,5,6) 中至少三个的 id 为该 id 的每一行返回 TRUE,为其他 id 返回 false。

id <- c(1,1,2,2,3,3,3,3)
time <- c(4,6,4,5,4,5,6,7)
df1 <- data.frame(id,time)
Run Code Online (Sandbox Code Playgroud)

解决方案

solution <-c(FALSE,FALSE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE)
df_w_sol <- data.frame(df1,solution)
Run Code Online (Sandbox Code Playgroud)

我正在尝试以下组合:

df1 %>%
  group_by(id) %>%
  mutate(INCLUDE = any(2:6 %in% time))
Run Code Online (Sandbox Code Playgroud)

但困难在于“5 个中的至少 3 个”部分,我认为这将包括 n > 部分。

Ron*_*hah 5

您可以使用sum来计算匹配的值的数量:

library(dplyr)
df1 %>% group_by(id) %>% mutate(solution = sum(2:6 %in% time) >= 3)

#    id  time solution
#  <dbl> <dbl> <lgl>   
#1     1     4 FALSE   
#2     1     6 FALSE   
#3     2     4 FALSE   
#4     2     5 FALSE   
#5     3     4 TRUE    
#6     3     5 TRUE    
#7     3     6 TRUE    
#8     3     7 TRUE    
Run Code Online (Sandbox Code Playgroud)

基本 R 的等价物

transform(df1, solution = ave(time, id, FUN = function(x)  sum(2:6 %in% x)) >= 3) 
Run Code Online (Sandbox Code Playgroud)

data.table

library(data.table)
setDT(df1)[, solution := sum(2:6 %in% time) >= 3, id]
Run Code Online (Sandbox Code Playgroud)