【发布时间】: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)
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)
我们可以使用grepl 来获得逻辑索引的vector,转换为与原始matrix('皇帝')相同维度的matrix,并用which 和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
或者另一种转换grepl 输出的方法是将dim 分配给'emperor' 的dim 并用which 包装。
which(`dim<-`(grepl('us', emperor), dim(emperor)), arr.ind=TRUE)
【讨论】: