0

I am looking for a way to sum an array along a specified dimension.

I was able to reproduce the example given in the MathWorks documentation for MATLAB. My R code refers to the following part of the MATLAB documentation:

A = ones(4,2,3);
S = sum(A,3)

%  Result:
%  S = 4×2  

%     3     3
%     3     3
%     3     3
%     3     3

An eqivalent in R would be:

matlabsum = matrix(1, 4*2*3)
dim(matlabsum) = matrix(c(4,2,3))
matlabsum
matlabsumEquivalent = rowSums(matlabsum,dims=2)
matlabsumEquivalent 

This returns the same result as in MATLAB. Now I am trying to replicate some MATLABcode in R. The MATLAB code looks like this (4 dimensions):

FtTEST = ones(2,3,3,16);
FtTESTsum = sum(FtTEST,4)

Same in R:

Ftmatlabsum = matrix(1, 2*3*3*16)
dim(Ftmatlabsum) = matrix(c(2,3,3,16))
Ftmatlabsum
FtmatlabsumEquivalent = rowSums(Ftmatlabsum,dims=3) # dims is: dims+1 with rowSums
FtmatlabsumEquivalent

My actual attempt in R is to apply the rowSums() function to a list that looks like this:

FtTEST = vector("list", 2*3*3*16)
dim(FtTEST) = matrix(c(2,3,3,16))
FtTEST[FtTEST == "NULL"] = 1 # Filling list with values of 1
Ftsum = rowSums(FtTEST,dims=3) # dims+1
Ftsum # ERROR

I only get Error in rowSums(FtTEST, dims = 3) : 'x' must be numeric as Error.

How do I convert my list properly?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • Why not convert the list to an array? One way , I think, is `un = unlist(FtTEST); dim(un) = dim(FtTEST)` – user20650 Nov 05 '21 at 14:16
  • 1
    Ok, I figured it out: FtTESTarr <- array(as.numeric(unlist(FtTEST)), dim = c(2, 3, 3, 16)) It then does rowSums() on it. Thanks!! – Steffen Schwerdtfeger Nov 05 '21 at 14:20
  • 2
    I feel like you can make this question a lot more understandable to an R user who doesn't understand MATLAB by simply removing all MATLAB references. All `sum(A,dim)` does, is sum a (multi-) dimensional matrix along the specified axis. That's a basic operation, which in my opinion, would not need an example in a different language. – Adriaan Nov 05 '21 at 14:20

1 Answers1

1

Ok, I figured it out:

FtTESTarr <- array(as.numeric(unlist(FtTEST)), dim = c(2, 3, 3, 16))

It then does rowSums() on it. Thanks to "user20650"!!