Is There an R Function for the Element-Wise Summation of the Matrices Stored as Elements in Single List Object

Is there an R function for the element-wise summation of the matrices stored as elements in single list object?

See ?Reduce.

From the example:

## A general-purpose adder:
add <- function(x) Reduce("+", x)

Then you can

add(myList)

How can I do list summation element-wise in R

We can use Map

Map(`+`, temp1, temp2)[[2]]

Sum of a list of matrices in R

Since you want to keep top-level list use lapply :

lapply(x, function(l) if(is.list(l)) Reduce(`+`, l) else l)

#[[1]]
# [,1] [,2] [,3]
#[1,] 3 9 15
#[2,] 5 11 17
#[3,] 7 13 19

#[[2]]
# [,1] [,2] [,3]
#[1,] 3 6 9
#[2,] 4 7 10
#[3,] 5 8 11

#[[3]]
# [,1] [,2] [,3]
#[1,] 4 7 10
#[2,] 5 8 11
#[3,] 6 9 12

Add together a list of matrices element-by-element

 > Reduce("+", m1.l)
[,1] [,2] [,3] [,4]
[1,] 1 0 0 0
[2,] 1 1 0 0
[3,] 1 1 1 0
[4,] 0 1 1 1
[5,] 0 0 1 1
[6,] 0 0 0 1
[7,] 0 0 0 0
[8,] 0 0 0 0
[9,] 0 0 0 0

This will add the first two together, then it will take the result and add the 3rd matrix to it. Then it will add that result to the fourth matrix, etc. until it's worked its way through the whole list.

Sum a list of matrices

Use Reduce.

## dummy data

.list <- list(matrix(1:25, ncol = 5), matrix(1:25, ncol = 5))

Reduce('+', .list)
## [,1] [,2] [,3] [,4] [,5]
## [1,] 2 12 22 32 42
## [2,] 4 14 24 34 44
## [3,] 6 16 26 36 46
## [4,] 8 18 28 38 48
## [5,] 10 20 30 40 50

adding elements in vectors (not matrices) in a list in R

Here is one way:

rowSums(simplify2array(lst))

where lst is your list.

Add together a list of matrices element-by-element

 > Reduce("+", m1.l)
[,1] [,2] [,3] [,4]
[1,] 1 0 0 0
[2,] 1 1 0 0
[3,] 1 1 1 0
[4,] 0 1 1 1
[5,] 0 0 1 1
[6,] 0 0 0 1
[7,] 0 0 0 0
[8,] 0 0 0 0
[9,] 0 0 0 0

This will add the first two together, then it will take the result and add the 3rd matrix to it. Then it will add that result to the fourth matrix, etc. until it's worked its way through the whole list.

How to get sum of each element in two matrices of R

As @Arun suggests, your question is hard to interpret. But, is this what you mean? (I presume you forgot to include 18 in your example.)

> a <- c(2,4,9)
> b <- c(3,6,9)
> sort(rowSums(expand.grid(a,b)))
[1] 5 7 8 10 11 12 13 15 18

Element-wise addition of two matrices/data frames

Element-wise addition is what + does with most objects:

> d <- data.frame(x=1:3, y=4:6)
> d
x y
1 1 4
2 2 5
3 3 6
> d2 <- data.frame(z=4:6, w=6:4)
> d + d2
x y
1 5 10
2 7 10
3 9 10

The names will come from the first data frame, and order of the columns in the two sets does matter. As yours are in the same order, you should be fine.

You'll get an error if the number of rows or columns differ.

Subtracting list elements from another list in R

I figured it out - I had another mistake in the question :/

Changing the second class as.numeric worked

lt3 = lapply(lt2[[1]],"-",as.numeric(lt[[1]]))



Related Topics



Leave a reply



Submit