hvgupta
hvgupta

Reputation: 199

How to create grouped edgelist from vector in R

Basically, I'd like to do this, but with a grouping variable.

For example, I have a dataframe,

data.frame(group = c(1, 1, 2, 2, 2), value = c("A", "B", "C", "D", "E", "F"))

and I want to convert it to an edgelist, by group:

from   to   group
A       B     1
C       D     2
D       E     2
E       F     2

Notice that there is no B -> C connection because they're in separate groups.

Anyone know how I would go about this?

Upvotes: 0

Views: 211

Answers (2)

akrun
akrun

Reputation: 887068

Using data.table

library(data.table)
setDT(df1)[, .(from = value, to = shift(value, type = 'lead')), 
       by = .(group)][!is.na(to)]
#.   group from to
#1:     1    A  B
#2:     2    C  D
#3:     2    D  E
#4:     2    E  F

Upvotes: 1

Onyambu
Onyambu

Reputation: 79208

library(tidyverse)
df%>%
   group_by(group)%>%
   mutate(from = value, to = lead(value), value = NULL)%>%
   na.omit()

  group from  to   
  <dbl> <fct> <fct>
1     1 A     B    
2     2 C     D    
3     2 D     E    
4     2 E     F    

Upvotes: 2

Related Questions