Home > Enterprise >  Generating all possible outcomes in r
Generating all possible outcomes in r

Time:10-04

Given a vector with numeric values, how do I generate all possible outcomes for subtraction to find the differences and put them in a data.frame?

dataset1 <- data.frame(numbers = c(1,2,3,4,5,6,7,8,9,10))

i.e. (1 - 1, 1 - 2 , 1 - 3,...)

Ideally, I would want the output to give me a data frame with 3 columns (Number X, Number Y, Difference) using dataset1.

CodePudding user response:

The expand.grid function can get you "pairings" which are different than the pairings you get with combn. Since you included 1-1 I'm assuming you didn't want since it doesn't return 1-1 and only gives you 45 combinations.

> pairs=expand.grid(X=1:10, Y=1:10)
> pairs$diff <- with(pairs, X-Y)
> pairs
     X  Y diff
1    1  1    0
2    2  1    1
3    3  1    2
4    4  1    3
5    5  1    4
6    6  1    5
7    7  1    6
8    8  1    7
9    9  1    8
10  10  1    9
11   1  2   -1
12   2  2    0
13   3  2    1
14   4  2    2
15   5  2    3
16   6  2    4
17   7  2    5
snipped remainder (total of 100 rows)

Use outer as another way to get such a group of paired differences;

> tbl <- matrix( outer(X=1:10, Y=1:10, "-"), 10, dimnames=list(X=1:10, Y=1:10))
> tbl
    Y
X    1  2  3  4  5  6  7  8  9 10
  1  0 -1 -2 -3 -4 -5 -6 -7 -8 -9
  2  1  0 -1 -2 -3 -4 -5 -6 -7 -8
  3  2  1  0 -1 -2 -3 -4 -5 -6 -7
  4  3  2  1  0 -1 -2 -3 -4 -5 -6
  5  4  3  2  1  0 -1 -2 -3 -4 -5
  6  5  4  3  2  1  0 -1 -2 -3 -4
  7  6  5  4  3  2  1  0 -1 -2 -3
  8  7  6  5  4  3  2  1  0 -1 -2
  9  8  7  6  5  4  3  2  1  0 -1
  10 9  8  7  6  5  4  3  2  1  0

But I didn't see a compact way to create a dataframe of the sort you specified.

The now deleted comment by @RitchieSacramento iswas correct:

> tbl <- matrix( outer(X=1:10, Y=1:10, "-"), 10, dimnames=list(X=1:10, Y=1:10))
> as.data.frame.table(tbl)
     X  Y Freq
1    1  1    0
2    2  1    1
3    3  1    2
4    4  1    3
5    5  1    4
6    6  1    5
7    7  1    6
8    8  1    7
9    9  1    8
10  10  1    9
11   1  2   -1
12   2  2    0
13   3  2    1
14   4  2    2
15   5  2    3
16   6  2    4

CodePudding user response:

You can use the combn() function to generate the list of all combinations take 2 at a time.

numbers = c(1,2,3,4,5,6,7,8,9,10)
output <-combn(numbers, 2, FUN = NULL, simplify = TRUE )

answer <- as.data.frame(t(output))
answer$Difference <- answer[ ,1] - answer[ ,2]

head(answer)

V1 V2 Difference
1  1  2         -1
2  1  3         -2
3  1  4         -3
4  1  5         -4
5  1  6         -5
6  1  7         -6
  • Related