How to link multiple IDs together in R?

151 views Asked by At

I have the following dataset pairs in id1 and id2 column which are all related to id 313. I am new to R and trying to find a solution that could link all those numbers to id 313. I tried using the sqldf join but does not turn out to be very effective.

id1<- c(313, 313, 313, 313, 313, 314, 314, 314, 314, 315, 317, 317, 317, 318, 318, 319)
id2<-c(314, 315, 316, 319, 320, 315, 316, 319, 320, 316, 318, 319, 320, 319, 320, 320)

df<-cbind.data.frame (id1, id2)

The desired output would look something like this.

id1   id2 id3 id4 id5 id6 id7 id8
313   314 315 316 317 318 319 320

So basically the idea is to group them together in one row so it is regarded as one id. Greatly appreciate any suggestion that can tie them together.

1

There are 1 answers

0
eastclintw00d On

Try this:

library(dplyr)
library(tidyr)

tibble(
  x1 = c(df$id1, df$id2) %>% unique()
) %>% 
  mutate(
    x2 = paste0("id", row_number())
  ) %>% 
  pivot_wider(names_from = x2, values_from = x1)