[R] Function that finds elements from matrix, and saves the indices of the elements to another matrix
Rui Barradas
ru|pb@rr@d@@ @end|ng |rom @@po@pt
Mon Sep 14 23:45:40 CEST 2020
Hello,
This is simple:
which(A == 1, arr.ind = TRUE)
Hope this helps,
Rui Barradas
Às 12:03 de 14/09/20, Tuomas Koponen escreveu:
> Hi all dear R-list users,
>
> This might sound a silly problem, but but for one reason or another it has
> proved unsolvable to me.
>
> I need to solve the following task. I have tried to use two nested for
> loops as a solution, but have not been able to made it work. It would be
> great, if someone could formulate a code for me:
>
> I need to create a function X that takes as its input a 10x10 matrix, which
> elements consists of ones and zeros. The function X must find the elements
> in the matrix A that are "ones", and save the indices of those elements in
> 2-column matrix, in a following way: the first column has a row number, and
> the second a column number.
>
> The answer should be formulated in a way, that it uses two nested for
> loops. The matrix to be returned has a maximum of 100 rows, so one
> possibility exists for a 100x2 matrix filled with zeros in the index and
> finally separate those rows with zeros.
>
> I have tried the following code:
>
> A<-matrix(1:0, nrow = 10, ncol = 10)
>
> X <- data.frame()
> for (i in seq(1, nrow(A))) {
> for (j in seq(1,ncol(A))) {
> if (A [i,j] > 0) {
>
> new_row <- data.frame(Row_number= rownames(A)[i], Column_number=
> colnames(A)[j])
>
> X <- rbind(X, new_row)
>
> }
>
> }
> }
>
> I only manage to get "Error: object 'X' not found", as a result.
>
> thanks in advance for your help.
>
> Br. Tuomas
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list