# [R] Function that finds elements from matrix, and saves the indices of the elements to another matrix

Bert Gunter bgunter@4567 @end|ng |rom gm@||@com
Mon Sep 14 21:11:20 CEST 2020

```Is this a homework problem? We try not to do others' homework here.

Incidentally, this can easily be done much more efficiently without any
for() loops.

Bert Gunter

"The trouble with having an open mind is that people keep coming along and
sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )

On Mon, Sep 14, 2020 at 11:50 AM Tuomas Koponen <tuomas.o.koponen using gmail.com>
wrote:

> 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.
>
>
> 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