I've got a logical matrix and I need to multiply each column by the sum of this column using apply. For example :
> a
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 0 0 0 0
[3,] 1 1 0 1
[4,] 1 0 0 1
> b <- colSums(a)
> b
[1] 3 2 1 3
And I want to get the following matrix :
> a
[,1] [,2] [,3] [,4]
[1,] 3 2 1 3
[2,] 0 0 0 0
[3,] 3 2 0 3
[4,] 3 0 0 3
I did it with for but since I need to apply my function to a huge dataset I need to code with apply. Thank you.
You can take the transpose ( t
) of the matrix 'a' and then multiply with the vector ('b'), take the transpose ( t
) of the output to get the desired result.
t(t(a)*b)
Or we can make the lengths of the 'a' and 'b' same by replicating the elements of 'b'. By doing b[col(a)]
, we get each element of 'b' replicated by the index provided by the col
.
a*b[col(a)]
For better understanding
col(a)
# [,1] [,2] [,3] [,4]
#[1,] 1 2 3 4
#[2,] 1 2 3 4
#[3,] 1 2 3 4
#[4,] 1 2 3 4
b[col(a)] #is a vector
#[1] 3 3 3 3 2 2 2 2 1 1 1 1 3 3 3 3
a*b[col(a)]
# [,1] [,2] [,3] [,4]
#[1,] 3 2 1 3
#[2,] 0 0 0 0
#[3,] 3 2 0 3
#[4,] 3 0 0 3
In addition to @akrun's answer, if you really do want to use apply
:
apply(a,2,function(x)x*sum(x))
# [,1] [,2] [,3] [,4]
#[1,] 3 2 1 3
#[2,] 0 0 0 0
#[3,] 3 2 0 3
#[4,] 3 0 0 3
2
means you work on columns (ie the second dimension). So each operation is done on a vector corresponding to a column, hence the use of sum
(which works on vector) instead of colSums
(which works on a matrix).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.