R: Returns the rows and column numbers of matches in a data frame

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

How do I return the row and column numbers of all cells that contain the sequence "us", ie [1,1], [1,2], [2,2]?

+3


source to share


1 answer


We could use grepl

to get a vector

boolean index, convert to matrix

the same size as the original matrix

('emperor'), and wrap which

with using 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 output grepl

is to assign an "emperor" dim

character dim

and terminate with which

.

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

      

+5


source







All Articles