Caspar van Lissa
Caspar van Lissa

Reputation: 123

R: Apply over every column of nXm matrix, return n*n*m array

What is the appropriate function to apply a function that returns an n*n matrix, over every column of a matrix/nXm array, and get back an nXnXm array? I can get it to work with a list:

dm <- structure(c(0.205292439079469, 0.222642769676055, 0.222786614980172, 
              0.210917067409095, 0.123955673451174, 0.10591537361648, 0.0887665882561804, 
              0.0725263089185602, 0.174088645938512, 0.171936521036433, 0.159619467190219, 
              0.143492610130578, 0.23303504847129, 0.269389294469438, 0.279103519495381, 
              0.240824583373471, 0.192637398624569, 0.201551950015116, 0.195748345926477, 
              0.181448686311511), .Dim = 4:5)
sapply(1:ncol(dm), function(x){dm[, x] %*% t(dm[, x])^-1}, simplify = F)

Thank you!

Upvotes: 0

Views: 45

Answers (1)

d125q
d125q

Reputation: 1666

Use simplify = "array" instead of simplify = F.

sapply(1:ncol(dm), function(x){dm[, x] %*% t(dm[, x])^-1}, simplify = "array")

Upvotes: 1

Related Questions