Reputation: 435
I am trying to construct a matrix that includes all the possible combinations. For example,
a=(1:2)^3 #=c(1,8)
b=(1:3)^2 #=c(1,4,9)
And I would like to define c
such that c=c(1+1,1+4,1+9,8+1,8+4,8+9)
. I have learned from my previous question on how to get such a c
from function outer
. My current question is, how can I get a matrix M
as follows:
Thanks in advance!
Upvotes: 1
Views: 82
Reputation: 887138
Or another option is CJ
library(data.table)
CJ(a, b)[, C := V1 + V2][]
#. V1 V2 C
#1: 1 1 2
#2: 1 4 5
#3: 1 9 10
#4: 8 1 9
#5: 8 4 12
#6: 8 9 17
Upvotes: 2
Reputation: 73315
OK, here it is:
z <- outer(b, a, "+")
cbind(a[col(z)], b[row(z)], c(z))
# [,1] [,2] [,3]
#[1,] 1 1 2
#[2,] 1 4 5
#[3,] 1 9 10
#[4,] 8 1 9
#[5,] 8 4 12
#[6,] 8 9 17
A slightly adapted expand.grid
solution.
ref <- expand.grid(b = b, a = a)
val <- do.call("+", ref) ## or `rowSums(ref)` with an implicit `as.matrix`
cbind(ref, c = val)
# b a c
#1 1 1 2
#2 4 1 5
#3 9 1 10
#4 1 8 9
#5 4 8 12
#6 9 8 17
In this case the result is a data frame rather than a matrix.
Upvotes: 5
Reputation: 388982
We can use expand.grid
with outer
data.frame(expand.grid(a, b), c = c(outer(a, b, "+")))
# Var1 Var2 c
#1 1 1 2
#2 8 1 9
#3 1 4 5
#4 8 4 12
#5 1 9 10
#6 8 9 17
where
outer(a, b, "+") #gives
# [,1] [,2] [,3]
#[1,] 2 5 10
#[2,] 9 12 17
Upvotes: 5