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]?
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.
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.
We can compare two columns in R by using ifelse(). This statement is used to check the condition given and return the data accordingly.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With