I am trying to execute a function for each cell of a data table in R, creating a second one based on the result of this loop. For example, imagine that I have a matrix A
Ad1 Ad2 Ad3 Ad4
AA 6 0 10
AB 7 10 12
AC 0 0 15
and I'm trying to create Matrix B
Ad1 Ad2 Ad3 Ad4
AA 1 0 1
AB 1 0 1
AC 0 0 1
so that each cell takes the value 1, if this cell has a value> 0 And the sum of the column is minus, that the cell is also greater than 0.
For example, AA ~ Ad2 is 6, and the sum of the column is 7 (6 + 7 + 0 - 6); then AA ~ Ad2 in the matrix B takes the value 1.
Is there a way to accomplish this without looping? I managed to do this with a loop, but it takes too much time:
A = read.table(text="Ad1 Ad2 Ad3 Ad4
AA 6 0 10
AA 7 10 12
AA 0 0 15", header=TRUE)
B = read.table(text="Ad1 Ad2 Ad3 Ad4
AA 0 0 0
AA 0 0 0
AA 0 0 0", header=TRUE)
for (i in 1:nrow(B)) {
for (j in 2:ncol(B)) {
if ((sum(A[,j], na.rm = T) - ifelse(is.na(A[i,j]), 0, A[i,j]))> 0 &
ifelse(is.na(A[i,j]), 0, A[i,j]) > 0 )
{B[i,j] <- 1}
}
}
source
share