【问题标题】:How to check if all multiple values in a list exist in a dataframe in R?如何检查列表中的所有多个值是否存在于 R 中的数据框中?
【发布时间】:2022-12-13 00:22:31
【问题描述】:

我有一个数据框 df,其中包含 ids = (1, 2, 3, 4),我有一个列表,项目,其中包含 ("a"、"b"、"c")。我想返回包含“a”、“b”和“c”的 ID。它不应该返回,除非 id 至少包含列表中的所有 3 个项目。

df <- data.frame(ID = (1, 2, 2, 3, 3, 3, 4, 4, 4, 4), values = ("b", "a", "c", "a", "b", "c", "a", "b", "c", "d"))
items <- list("a", "b", "c")

df 看起来像: |编号 |价值观 | |-----|--------| |1 |乙 | |2 |一个 | |2 | c | |3 |一个 | |3 |乙 | |3 | c | |4 |一个 | |4 |乙 | |4 | c | |4 | d |

该函数应返回 ID = (3, 4),但对于 ID = 4,应仅返回 values = ("a", "b", "c")。它不应返回 ID = (1, 2)。 这是我尝试过的,但它没有返回我想要的。

  Criteria.Match <- function(df, CriteriaList, criteria.string){
   Pat <- as.data.frame(unique(df$ID))
   colnames(Pat) <- 'ID'
   Pat.Criteria_Type <- as.data.frame(unique(df[c('ID', criteria.string)]))
   Pat$CriteriaMet <- sapply(Pat$ID, FUN = function(x){
   setequal(Pat.Criteria_Type[Pat.Criteria_Type$ID == x,], as.data.frame(CriteriaList))
  })
   Pat <- Pat[which(Pat$CriteriaMet),]
   df[df$ID %in% Pat$ID,]
}

Criteria.Match(df, items, 'values')

【问题讨论】:

    标签: r string list dataframe comparison


    【解决方案1】:

    桌子,然后子集使用行总和:

    x <- table(df)[, unlist(items) ]
    rownames(x)[ which(rowSums(x) == 3) ]
    # [1] "3" "4"
    

    【讨论】:

      【解决方案2】:

      根据项目中的值对 df 中的项目进行子集化。然后,循环遍历每个ID,检查过滤后的df的行数是否等于items列表的长度。然后过滤掉 FALSE 值和子集 df 仅是过滤后的 df 中存在的 id。

      df <- df[df$values %in% items,]
      for(id in df$ID){
        df_filter <- df %>% filter(ID == id)
        df_filter$Criteria[df_filter$ID == id] <- nrow(unique(df_filter %>% select(values))) >= length(items)
            }
      df_filter <- df_filter %>% filter(Criteria == TRUE)
      df <- df[df$ID %in% df_filter$ID,]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        • 2020-02-10
        • 1970-01-01
        • 2021-03-05
        • 2012-01-26
        相关资源
        最近更新 更多