[R] Function that finds elements from matrix, and saves the indices of the elements to another matrix
Tuomas Koponen
tuom@@@o@koponen @end|ng |rom gm@||@com
Mon Sep 14 13:03:01 CEST 2020
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]]
More information about the R-help
mailing list