R:返回数据帧中匹配的行号和列号

das*_*asf 5 indexing search r

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

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

akr*_*run 7

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

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

或者另一种方式的转换grepl输出是通过分配dim到的dim"皇帝",并与包装which.

 which(`dim<-`(grepl('us', emperor), dim(emperor)), arr.ind=TRUE)
Run Code Online (Sandbox Code Playgroud)