0

I have a dataframe:

data.frame(x=c(1,2,3), y=c(4,5,6))

  x y
1 1 4
2 2 5
3 3 6

For each row, I want to repeat x and y for each element within a given sequence, where the sequence is:

E=seq(0,0.2,by=0.1)

So when combined this would give:

  x y E
1 1 4 0
2 1 4 0.1
3 1 4 0.2
4 2 5 0
5 2 5 0.1
6 2 5 0.2
7 3 6 0
8 3 6 0.1
9 3 6 0.2 

I can not seem to achieve this with expand.grid - seems to give me all possible combinations. Am I after a cartesian product?

Anthony W
  • 1,289
  • 2
  • 15
  • 28
  • I was asking specifically if this was a cartesian product. I dont see this mentioned in the suggested answer? – Anthony W May 02 '20 at 08:42

2 Answers2

2
library(data.table)
dt <- data.table(x=c(1,2,3), y=c(4,5,6))

dt[,.(E=seq(0,0.2,by=0.1)),by=.(x,y)]
#>    x y   E
#> 1: 1 4 0.0
#> 2: 1 4 0.1
#> 3: 1 4 0.2
#> 4: 2 5 0.0
#> 5: 2 5 0.1
#> 6: 2 5 0.2
#> 7: 3 6 0.0
#> 8: 3 6 0.1
#> 9: 3 6 0.2

Created on 2020-05-01 by the reprex package (v0.3.0)

Frank Zhang
  • 1,670
  • 7
  • 14
1

Yes, you are looking for cartesian product but base expand.grid cannot handle dataframes.

You can use tidyr functions here :

tidyr::expand_grid(df, E)

# A tibble: 9 x 3
#      x     y     E
#  <dbl> <dbl> <dbl>
#1     1     4   0  
#2     1     4   0.1
#3     1     4   0.2
#4     2     5   0  
#5     2     5   0.1
#6     2     5   0.2
#7     3     6   0  
#8     3     6   0.1
#9     3     6   0.2

Or with crossing

tidyr::crossing(df, E)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213