【问题标题】:R: Identify (partial) matching cellsR:识别(部分)匹配的单元格
【发布时间】:2021-10-31 17:38:09
【问题描述】:

我有一张包含数千行数百列的表格。我需要识别(部分)匹配多个关键字的单元格,而不是过滤表格。 到目前为止,我能找到的只是函数 WhichCells {SeuratObject} - 可惜我无法让它工作。

例如

Column1 <- c("Temperature", "Water", "Sun", "tree fighter", "rainbow")
Column2 <- c(60.1, 106, 78.6, 21.5, 71)
Column3 <- c("Another cell", NA, "more content", NA, "Thanks!")
    
df <- data.frame(Column1, Column2, Column3)
df

pattern <- c("temp", "content", 55, "heart", "thanks")

想要的结果是这样的

pattern   Column    Row
1    temp Column1   1
2 content Column3   3
3  thanks Column3   5

注意:行也可以作为行名返回。

请问,谁能给点建议如何解决这个问题?非常感谢!

【问题讨论】:

    标签: r string-matching


    【解决方案1】:

    在这里,这是答案的一部分,但您应该做一些调整以考虑大写/小写:

    pattern <- c("Temp", "content", 55, "heart", "Thanks")
    
    detectpattern <- function(df, pattern){
        colindex <- which(apply(df, 1, str_detect, pattern = pattern))
        rowindex <- which(apply(df, 2, str_detect, pattern = pattern))
        return(c(pattern, colindex, rowindex))
    }
    
    for (pat in pattern){
        print(detectpattern(df = df, pattern = pat))
    }
    

    【讨论】:

      【解决方案2】:

      你可以试试

      df %>%
        tibble::rownames_to_column(., var = "Row") %>%
        melt(id.vars = "Row", value.name = "patterns", variable.name = "Column") %>% 
        mutate(check = ((sapply(pattern, function(x) {str_detect(patterns, regex(x, ignore_case = T)) %>% as.numeric} ))%>% rowSums(., na.rm=TRUE))) %>%
        filter(check == 1) %>% select(-check)
      
      
        Row  Column     patterns
      1   1 Column1  Temperature
      2   3 Column3 more content
      3   5 Column3      Thanks!
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-28
        • 2016-10-21
        • 2016-07-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多