将函数应用于R中矩阵的每个像元 [英] Apply function to each cell of matrix in R

查看:74
本文介绍了将函数应用于R中矩阵的每个像元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对R中的数据表的每个单元执行一项功能,并基于此循环的结果创建第二个单元.例如,假设我有矩阵A

I'm trying to perform a function to each cell of a data table in R, creating a second one based on the result of this loop.. For example, imagine I have Matrix A

    Ad1    Ad2    Ad3    Ad4
    AA      6       0     10
    AB      7      10     12
    AC      0       0     15

我正在尝试创建矩阵B

and I'm trying to create Matrix B

    Ad1    Ad2    Ad3    Ad4
    AA      1       0      1
    AB      1       0      1
    AC      0       0      1

如果该单元格的值> 0,则每个单元格都将假定值为1. AND 列的总和减去该单元格也大于0.

in a way that each cell assumes the value 1 if that cell has a value > 0 AND the sum of the column minus that cell is also greater than 0.

例如,AA〜Ad2为6,列的总和为7(6 + 7 + 0-6);则矩阵B中的AA〜Ad2取值为1.

For instance, AA~Ad2 is 6 and the sum of the column is 7 (6 + 7 + 0 - 6); then AA~Ad2 in matrix B assumes value 1.

有没有一种方法可以执行此操作而不执行循环?我已经设法通过循环来做到这一点,但是它花费的时间太长:

Is there a way to perform this without performing a loop? I've managed to do this with a loop but it is taking too long:

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

推荐答案

我们可以通过创建两个逻辑矩阵来实现无循环操作-1)检查数字列的值是否大于0(A[-1] > 0),2)检查列总和与列值的差是否也大于0.如果它们都为TRUE(&条件),则将逻辑矩阵转换为二进制(+)并将其分配给数据集(A[-1])

We can do this without a loop by creating two logical matrices -1) check whether the numeric column values are greater than 0 (A[-1] > 0), 2) check whether the difference of the column sums with the column values are also greater than 0. If both of them are TRUE (& condition), convert the logical matrix to binary (+) and assign it to the subset of the dataset (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

这篇关于将函数应用于R中矩阵的每个像元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆