2017-07-04 47 views
2

我有一個節點的數據幀。數據框可以用此來創建,R DataFrame:鏈接數據的條件轉換

t1 <- c(1,0,1,0,1) #type 1 
t2 <- c(1,0,1,0,1) #type 1 

t3 <- c(1,1,0,0,1) #type 2 
t4 <- c(1,1,0,0,1) #type 2 

t5 <- c(1,0,1,0,1) #type 1 
t6 <- c(1,0,1,0,1) 


df <- data.frame(rbind(t1,t2,t3,t4,t5)) 
names(df) <- c('n1','n2','n3','n4','n5') 
df 

數據框看起來是這樣的,

n1 n2 n3 n4 n5 
t1 1 0 1 0 1 
t2 1 0 1 0 1 
t3 1 1 0 0 1 
t4 1 1 0 0 1 
t5 1 0 1 0 1 

我想達到變換數據幀類似於鄰接指標。第一行可以轉化這樣,

n1 n3 1 # Means, 1 link from n1 to n3 
n3 n5 1 # Means, 1 link from n3 to n5 

又如,第四行應變換這樣,

n1 n2 1 
n2 n5 1 

現在的問題是,我可以做到這一點使用任何內置R中功能?

回答

1

來自tidyverse的解決方案。 df2是最終的輸出。

# Load packages 
library(tidyverse) 

# Process the data 
df2 <- df %>% 
    rownames_to_column("ID") %>% 
    gather(From, Occur, -ID) %>% 
    arrange(ID, From) %>% 
    filter(Occur != 0) %>% 
    group_by(ID) %>% 
    mutate(To = lead(From)) %>% 
    drop_na(To) %>% 
    select(ID, From, To, Occur) 

# View the result. df2 holds the transformed data 
df2 
# A tibble: 10 x 4 
# Groups: ID [5] 
     ID From To Occur 
    <chr> <chr> <chr> <dbl> 
1 t1 n1 n3  1 
2 t1 n3 n5  1 
3 t2 n1 n3  1 
4 t2 n3 n5  1 
5 t3 n1 n2  1 
6 t3 n2 n5  1 
7 t4 n1 n2  1 
8 t4 n2 n5  1 
9 t5 n1 n3  1 
10 t5 n3 n5  1 
+0

謝謝@ycw。它爲我工作。 –