0

I have a data frame of ids with number column

df <- read.table(text="
   id     nr 
   1      1   
   2      1  
   1      2     
   3      1    
   1      3    
", header=TRUE)

I´d like to create new dataframe from it, where each id will have unique nr from df dataframe. As you may notice, id 3 have only nr 1, but no 2 and 3. So result should be.

result <- read.table(text="
   id     nr 
   1      1   
   1      2  
   1      3     
   2      1    
   2      2 
   2      3 
   3      1    
   3      2 
   3      3  
", header=TRUE)
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
Sklenicka
  • 595
  • 2
  • 4
  • 16

2 Answers2

2

You can use expand.grid as:

library(dplyr)
result <- expand.grid(id = unique(df$id), nr = unique(df$nr)) %>%
  arrange(id)
result
 id nr
1  1  1
2  1  2
3  1  3
4  2  1
5  2  2
6  2  3
7  3  1
8  3  2
9  3  3
Sonny
  • 3,083
  • 1
  • 11
  • 19
0

We can do:

tidyr::expand(df,id,nr)
# A tibble: 9 x 2
     id    nr
  <int> <int>
1     1     1
2     1     2
3     1     3
4     2     1
5     2     2
6     2     3
7     3     1
8     3     2
9     3     3
NelsonGon
  • 13,015
  • 7
  • 27
  • 57