Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

indexing

search

r

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

like image 847
dasf Avatar asked May 02 '15 15:05

dasf


People also ask

How do I find the number of rows and columns in a Dataframe in R?

The ncol() function in R programming R programming helps us with ncol() function by which we can get the information on the count of the columns of the object. That is, ncol() function returns the total number of columns present in the object.

How do I count the number of items in a data frame in R?

To get number of rows in R Data Frame, call the nrow() function and pass the data frame as argument to this function. nrow() is a function in R base package.

How do I compare two columns in an R data frame for an exact match?

We can compare two columns in R by using ifelse(). This statement is used to check the condition given and return the data accordingly.

How do I return a row number in a Dataframe in R?

Rownames can also be assigned to the rows in a dataframe using the rownames() method. It takes a vector of length equivalent to the number of rows in the dataframe. The rownames(df) can also be checked to compare a value and then return a row number which corresponds to it.


1 Answers

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)
like image 112
akrun Avatar answered Sep 28 '22 06:09

akrun