Is there an R function for cell-based functions across multiple tables?

Viewed 60

I'm trying to find an R function that will allow me to take a cell-wise sum (or any anonymous function) across an arbitrary number of dataframes (which could be grouped together in a list).

One way to think of this could be that there is colsum, rowsum, but no cellsum.

purrr::pmap doesn't seem to help with this, since it doesn't allow for anonymous functions with an arbitrary number of arguments.

Images showing the three axes of functions: column-based (e.g. colsum), row-based (e.g. rowsum), and cell-based across multiple tables (e.g. ???)

3 Answers

You can use Reduce.

x <- data.frame(0:2, 2:0)
y <- data.frame(1:3, 3:1)
z <- list(x, y)

Reduce(`+`, z)
#  X0.2 X2.0
#1    1    5
#2    3    3
#3    5    1

or create an array and use apply.

A <- simplify2array(lapply(z, as.matrix))
apply(A, 1:2, sum)
#     X0.2 X2.0
#[1,]    1    5
#[2,]    3    3
#[3,]    5    1

I think if your df is stored as a list, you could create a function for that:

a = data.frame(replicate(10,rnorm(10)))
b = data.frame(replicate(10,rnorm(10)))
c = data.frame(replicate(10,rnorm(10)))
d = list(a,b,c)

Cellsum = function(list , row, col){
  sum(unlist(lapply(list, function(i){return(i[row,col])})))
}
Cellsum(d,1,5)

Let me know if it worked

Since you suggested purrr, how about a two step approach?

dataframes <- list(diag(3), diag(3)*2)
map_dbl(dataframes, ~.x[1,1]) %>% sum()
Related