【问题标题】:Return the row and column position of R data frame where the cell value matches a pattern返回单元格值与模式匹配的 R 数据框的行和列位置
【发布时间】:2020-02-25 18:34:42
【问题描述】:

我有一个数据框

structure(list(Brand = c("AB", "AC", "AD", "BA", "CB", "CK"), `&TV` = c("0_640", 
"0", "1_340", "0", "0", "0"), `&TV HD` = c("1_500", "0", "0_140", 
"0", "0", "0")), row.names = c(NA, 6L), class = "data.frame")

看起来像这样:

  Brand   &TV &TV HD
1    AB 0_640  1_500
2    AC     0      0
3    AD 1_340  0_140
4    BA     0      0
5    CB     0      0
6    CK     0      0

我想返回那些包含1_ 模式的单元格的行和列值。对于上面的例子,我想返回

row col
3    2
1    3

我正在尝试使用 grep 但不是很成功。

grep(New_Brands_Theme_Combine[,c(1:length(New_Brands_Theme_Combine))], pattern = "1_")

上面给出了找到模式的数据框的列号。如何获取列号和行号。

【问题讨论】:

    标签: r


    【解决方案1】:

    一个选项是遍历感兴趣的列('colnm'),应用grep 来获取位置索引,将listnames 设置为列索引,并将stack 设置为两列data.frame

    colnm <- 2:3
    out <- stack(setNames(lapply(df1[colnm], grep, pattern = "1_"), colnm))
    names(out) <- c("row",  "col")
    out
    #  row col
    #1   3   2
    #2   1   3
    

    【讨论】:

    • 无法相信您能以多快的速度解决问题并提出解决方案......非常感谢......解决方案完美运行......我会在 10 分钟内接受它.
    【解决方案2】:

    一个base R 选项可以是:

    which(matrix(grepl("1_", unlist(df)), dim(df)), arr.ind = TRUE)
    
         row col
    [1,]   3   2
    [2,]   1   3
    

    甚至:

    which(sapply(df, grepl, pattern = "1_"), arr.ind = TRUE)
    

    【讨论】:

      猜你喜欢
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 2021-12-27
      相关资源
      最近更新 更多