Paul Hoffmann
Paul Hoffmann

Reputation: 7

Outer Sum in R?

I am just a beginner in R, but could not find a solution for my problem so far. How can I create a matrix out of two vectors like this? In Excel it's totally easy, but how can I do this in R?

A = c(10,15,30)
B = transpose(A) --> the transposed matrix of A
=>  10
    15 
    30

I also want to make the calculation: A/(A+B) --> 10/(10+10) = 0.5 ; 15/(15+10) = 0.6 and so on.

So that I get a n x n Matrix with probabilities in the end like this:

                10   15   30
           10   0.5  0.6  0.75
VResult =  15   0.4  0.5  0.66
           30   0.25 0.33 0.5

I need to apply this easy example to a Vector with 32 numbers so I need a way to calculate this. The new matrix should then be saved. It would be really nice if you guys could help me out!

Upvotes: 0

Views: 1493

Answers (2)

Gladwell
Gladwell

Reputation: 328

There is already a function for outer but maybe it's better to write one so you get exactly what you want

outerMat <- function(V) {
    n = length(V)
    X = rep(V, each = n)
    Y = rep(V, times = n)
    M = matrix(X / (X + Y), nrow = n)
    return(M)
}

A <- c(10, 15, 30)

outerMat(A)
     [,1]      [,2]      [,3]
[1,] 0.50 0.6000000 0.7500000
[2,] 0.40 0.5000000 0.6666667
[3,] 0.25 0.3333333 0.5000000

This takes about 65 ms with a vector of length 1000 so should be ok for your purposes! The equivalent outer function takes about half the time.

Upvotes: 1

MrFlick
MrFlick

Reputation: 206207

Assuming that B always has the same values as A, you can just use

outer(A, A, FUN=function(x,y) y/(x+y))

Upvotes: 2

Related Questions