# [Rd] Subsetting "dspMatrix" without coercion to "matrix"

Martin Maechler m@ech|er @end|ng |rom @t@t@m@th@ethz@ch
Sun Nov 21 22:43:02 CET 2021

```>>>>> Mikael Jagan
>>>>>     on Wed, 17 Nov 2021 17:01:00 -0500 writes:

>> This seems entirely avoidable, given that there is a relatively simple
>> formula for converting 2-ary indices [i,j] of S to 1-ary indices k of
>> S[lower.tri(S, TRUE)]:
>>
>> k <- i + round(0.5 * (2L * n - j) * (j - 1L)) # for i >= j

> I ought to be slightly more precise here: _coercion_ is avoidable,
> because we can always map [i,j] to [k], but memory limits are not.
> Certainly S using x[k] cannot be arbitrarily long...

> At the very least, it would be convenient if the subset were performed
> efficiently whenever dimensions would be dropped anyway:

> * S[i, ] and S[, j] where i and j are vectors indexing exactly zero or
> one rows/columns
> * S[i] where i is a matrix of the form cbind(i, j)

I agree that this could be improved in the Matrix package;
One reason this never happened is probably that we (the Matrix
package authors) never had a relevant use case for speeding
these up.

Would you be interested in collaboration to improve the Matrix
package to achieve this?

Best regards,
Martin

> This would support, e.g., a memory-efficient 'apply' analogue without
> any need for MARGIN...

> applySymmetric <- function(X, FUN, ..., simplify = TRUE, check = TRUE) {
>   if (check && !isSymmetric(X)) {
>     stop("'X' is not a symmetric matrix.")
>   }
>   ## preprocessing
>   ans <- vector("list", n)
>   for (i in seq_len(n)) {
>     ans[[i]] <- forceAndCall(1L, FUN, S[i, ], ...)
>   }
>   ## postprocessing
>   ans
> }

> ______________________________________________
> R-devel using r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel

```