I have two tables the first is a single column with Subject Ids and the second is a single column with the Visit Names
library(tibble)
subjects <- tibble("Subject Id" = c("1-1", "1-2", "1-3"))
# A tibble: 3 x 1
`Subject Id`
<chr>
1 1-1
2 1-2
3 1-3)
visits <- tibble("Visits" = c("a", "b", "c"))
# A tibble: 3 x 1
Visits
<chr>
1 a
2 b
3 c
And I want to create a table that looks like this so I see every potential visit for every subject.
| Subject ID | Visits |
|---|---|
| 1-1 | a |
| 1-1 | b |
| 1-1 | c |
| 1-2 | a |
| 1-2 | b |
| 1-2 | c |
I’ve been trying to find a good solution, but all of the similar questions I find go back to doing a merge and that doesn’t seem like the correct solution for what I want to do.
>Solution :
We can use crossing
library(tidyr)
crossing(subjects, visits)
-output
# A tibble: 9 × 2
`Subject Id` Visits
<chr> <chr>
1 1-1 a
2 1-1 b
3 1-1 c
4 1-2 a
5 1-2 b
6 1-2 c
7 1-3 a
8 1-3 b
9 1-3 c
Or using base R
expand.grid(c(subjects, visits))
Subject Id Visits
1 1-1 a
2 1-2 a
3 1-3 a
4 1-1 b
5 1-2 b
6 1-3 b
7 1-1 c
8 1-2 c
9 1-3 c