Apply a function to each matrix cell in R

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}
    }
}
+4
source share
4 answers

, : -1) , 0 (A[-1] > 0), 2) , 0. TRUE ( &), (+) (A[-1])

A[-1] <-  +(colSums(A[-1])[col(A[-1])]-A[-1]>0 & A[-1] > 0)
A
#  Ad1 Ad2 Ad3 Ad4
#1  AA   1   0   1
#2  AB   1   1   1
#3  AC   0   0   1
+6

R 2 . , . , , 0, , - , . rep .

# extract matrix from data.frame
myMat <- as.matrix(A[-1])
# calculate result and store in data.frame
A[-1] <- (myMat > 0) * ((rep(colSums(myMat), each=nrow(myMat))- myMat) > 0)
A
  Ad1 Ad2 Ad3 Ad4
1  AA   1   0   1
2  AA   1   0   1
3  AA   0   0   1
+1

, , :

(A > 0 & (colSums(A) - A > 0)) * 1.0

& , , , .

In itself, each of them creates a logical matrix of the same size as A. It then &allows you to combine the logical matrices to generate a new one when the cells are TRUE only if the cells are TRUE in both input matrices.

Finally, * 1.0translates the logical matrix into a numerical one.

+1
source

You can also do:

m <- as.matrix(A[,-1])
colsm <- matrix(colSums(m), ncol = ncol(m), nrow = nrow(m), byrow = T)
(colsm-m)>0 & m>0)*1

#    Ad2 Ad3 Ad4
#[1,]   1   0   1
#[2,]   1   0   1
#[3,]   0   0   1
0
source

Source: https://habr.com/ru/post/1661189/


All Articles