R:返回数据帧中匹配项的行和列号 [英] R: return row and column numbers of matches in a data frame

查看:252
本文介绍了R:返回数据帧中匹配项的行和列号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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]?

推荐答案

我们可以使用grepl获取逻辑索引的vector,转换为与原始matrix相同尺寸的matrix( 'emperor'),然后用whicharr.ind=TRUE换行.

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

或转换grepl输出的另一种方法是将dim分配给'emperor'的dim并用which包装.

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)

这篇关于R:返回数据帧中匹配项的行和列号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆