R: return 数据框中匹配的行数和列数

R: return row and column numbers of matches in a data frame

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

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

我们可以用grepl得到一个vector的逻辑索引,转换成一个matrix与原来的matrix相同的维度('emperor') 并用 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)