user2117258
user2117258

Reputation: 515

R change data.frame structure from pairwise columns to pairwise rows

Change this:

From        To
A           D
B           E
C           F

to:

From        To
A           B
B           C
D           E
E           F

My data contains several hundred lines and not 3 as in the example.

Note: To clarify the names in the initial data.frame are two separate paths that I want to format into an edge list. I do not want to connect the two paths.

In this case we want to void the edge between C and D.

Upvotes: 0

Views: 94

Answers (3)

CPak
CPak

Reputation: 13581

Data

df <- data.frame(From=LETTERS[1:3], To=LETTERS[4:6], stringsAsFactors=F)

Solution splitting paths

library(dplyr)
df1 <- data.frame(From = head(unlist(df),-1), To = head(lead(unlist(df)),-1)) %>%
           filter(row_number() != nrow(df))

Explanation

unlist linearizes your df by column. lead moves entries up a position.

Output

  From To
1    A  B
2    B  C
3    D  E
4    E  F

Upvotes: 1

M--
M--

Reputation: 28955

All in Base R:

#[-nrow(dat), ] This removes the link between to columns (i.e. From C To D row)
data.frame(From = unlist(dat)[-length(unlist(dat))], To = unlist(dat)[-1], 
    row.names = NULL)[-nrow(dat), ] 

##   From To
## 1    A  B
## 2    B  C
## 4    D  E
## 5    E  F

Data:

 dat <- structure(list(From = structure(1:3, .Label = c("A", "B", "C"      
     ), class = "factor"), To = structure(1:3, .Label = c("D", "E",        
     "F"), class = "factor")), .Names = c("From", "To"), row.names = c(NA, 
     3L), class = "data.frame")  

Upvotes: 2

BENY
BENY

Reputation: 323306

try this using zoo ?

A=c(Data$From,Data$To)
B=as.data.frame(zoo::rollapply(A,2,paste))


  V1 V2
1  A  B
2  B  C
3  C  D
4  D  E
5  E  F
B[!B$V1%in%Data$From[length(Data$From)],]

  V1 V2
1  A  B
2  B  C
4  D  E
5  E  F

PS . change the name by using names(df)=c('Form','To')

Upvotes: 2

Related Questions