jtr13
jtr13

Reputation: 1277

How do I create an addition table in R?

This should be easy but I can't think of a more elegant way to create an addition table, such as:

x <- 1:3
cbind(x + x[1], x + x[2], x + x[3])

     [,1] [,2] [,3]
[1,]    2    3    4
[2,]    3    4    5
[3,]    4    5    6

I tried various versions of lapply() to no avail.

Upvotes: 1

Views: 181

Answers (2)

989
989

Reputation: 12935

You could do this:

m <- diag(length(x))
m[] <- x[col(m)] + x[row(m)]

#     [,1] [,2] [,3]
#[1,]    2    3    4
#[2,]    3    4    5
#[3,]    4    5    6

OR

matrix(x,length(x),length(x),byrow = TRUE) + x

Upvotes: 2

d.b
d.b

Reputation: 32548

You can either use outer or sapply or expand.grid (in combination with rowSums)

x = 1:3
outer(x, x, "+")
#     [,1] [,2] [,3]
#[1,]    2    3    4
#[2,]    3    4    5
#[3,]    4    5    6

sapply(seq_along(x), function(i) sapply(seq_along(x), function(j) x[i]+x[j]))
#     [,1] [,2] [,3]
#[1,]    2    3    4
#[2,]    3    4    5
#[3,]    4    5    6

matrix(rowSums(expand.grid(x, x)), ncol = length(x))
#     [,1] [,2] [,3]
#[1,]    2    3    4
#[2,]    3    4    5
#[3,]    4    5    6

Upvotes: 3

Related Questions