问题
emperor <- rbind(cbind('Augustus','Tiberius'),cbind('Caligula','Claudius'))
How do I return the row and column numbers of all the cells that contain the sequence 'us', i.e. [1,1], [1,2], [2,2]?
回答1:
We could use grepl
to get a vector
of logical index, convert to a matrix
of the same dimension as the original matrix
('emperor') and wrap with which
with 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
Or another way to convert the grepl
output is by assigning the dim
to that of the dim
of 'emperor' and wrap with which
.
which(`dim<-`(grepl('us', emperor), dim(emperor)), arr.ind=TRUE)
来源:https://stackoverflow.com/questions/30003929/r-return-row-and-column-numbers-of-matches-in-a-data-frame