Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to apply a visit names to subject IDs using data from two tables

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading