【问题标题】:R: return row and column numbers of matches in a data frameR:返回数据框中匹配的行数和列数
【发布时间】:2015-07-12 07:00:46
【问题描述】:

emperor <- rbind(cbind('Augustus','Tiberius'),cbind('Caligula','Claudius'))

如何返回包含序列“us”的所有单元格的行号和列号,即[1,1]、[1,2]、[2,2]?

【问题讨论】:

  • 试试which(matrix(grepl('us', emperor), ncol=2), arr.ind=TRUE)

标签: r search indexing


【解决方案1】:

我们可以使用grepl 来获得逻辑索引的vector,转换为与原始matrix('皇帝')相同维度的matrix,并用whicharr.ind=TRUE 包装.

which(matrix(grepl('us', emperor), ncol=ncol(emperor)), arr.ind=TRUE)
#     row col
#[1,]   1   1
#[2,]   1   2
#[3,]   2   2

或者另一种转换grepl 输出的方法是将dim 分配给'emperor' 的dim 并用which 包装。

 which(`dim<-`(grepl('us', emperor), dim(emperor)), arr.ind=TRUE)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    相关资源
    最近更新 更多