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

╄→гoц情女王★ 提交于 2019-12-22 06:54:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!