2017-01-20 4 views
1

にエッジをIGRAPH置くために、私は動物の名を持つデータフレームを持っている:がどのように正しい順序

df <- data.frame(
    col1 = c("dog", "cat", "bird", "mammal", "avis", "canis", "feline"), 
    col2 = c("canis", "feline", "avis", "animal", "animal", "mammal", "mammal")) 

library(igraph) 

species <- union(df$col2, df$col1) 
df <- df[c('col2', 'col1')] 
names(df) <- c('from', 'to') 
species <- species[order(species)] 
species <- sort(union(df$col2, df$col1)) 
g <- graph.data.frame(df, directed = TRUE, vertices = species) 
plot(g,vertex.size=2, vertex.label.dist=0.5, vertex.color="cyan", 
edge.arrow.size=0.5, layout=layout.reingold.tilford(g)) 

私は、コードを実行した後、私は、この図(下の画像)を取得します。データフレームの最初の3つの要素は"dog", "cat", "bird"で、グラフでは"bird", "dog", "cat"です。要するに、単語の順序が逆転し、データフレームを変更することなく、その特定の順序でそれらを欲しい。私は私のデータになりたいどのような順序でIGRAPHを伝えるために

enter image description here

は、それがこのまたは他では動作しません単一の文字を持っているデータフレームで正常に動作している間、私は、このコード行species <- species[order(species)]を使用して表しますフルワードを使用するデータフレーム。

答えて

2

現在のところ、頂点はベクトルspeciesの順序に従って並べられています。 vertices引数がない場合、順序は2列のデータフレームdfの結合要素に従います。

> g <- graph.data.frame(df, directed = TRUE) 
> V(g)$name 
[1] "canis" "feline" "avis" "animal" "mammal" "dog" "cat" "bird" 
> g <- graph.data.frame(df, directed = TRUE, vertices = species) 
> V(g)$name 
[1] "animal" "avis" "bird" "canis" "cat" "dog" "feline" "mammal" 

は、あなたの問題を解決 dfの2列の組合によるとspeciesベクトルを並べ替えるが、第一、第二の列を取ります。このようにして、 "dog", "cat", "bird"配列は speciesベクターを導く。

df <- data.frame(
    col1 = c("dog", "cat", "bird", "mammal", "avis", "canis", "feline"), 
    col2 = c("canis", "feline", "avis", "animal", "animal", "mammal",  "mammal")) 

library(igraph) 

df <- df[c('col2', 'col1')] 
names(df) <- c('from', 'to') 
species <- union(df$to, df$from) #NOTE do not sort the vector! 
g <- graph.data.frame(df, directed = TRUE, vertices = species) 
plot(g,vertex.size=2, vertex.label.dist=0.5, vertex.color="cyan", 
    edge.arrow.size=0.5, layout=layout.reingold.tilford(g)) 

ここで、頂点は種の順番に従って並べられ、"dog", "cat", "bird"が最初に配置されます。

> species 
[1] "dog" "cat" "bird" "mammal" "avis" "canis" "feline" "animal" 
> V(g)$name 
[1] "dog" "cat" "bird" "mammal" "avis" "canis" "feline" "animal" 

enter image description here

1

このような意味ですか?

enter image description here

私は、データなどの順並び替え:

df <- data.frame(from = c('animal', 'animal', 'mammal', 'mammal', 'avis', 'canis', 'feline'), 
       to = c('mammal', 'avis', 'canis', 'feline', 'bird', 'dog', 'cat')) 

IGRAPHプロットは、データフレームと異なるedgelistの順でエッジ:

get.edgelist(g) 

この変更が必要な情報です。私は小さなグラフを作成しただけで、いつも自分が望む順番でデータを入力しましたが、これはset.edge.attribute()を調査するためのものだと思います。

+0

私は私のコードで 'get.edgelist(G)'や 'set.edge.attributeを()'を使用する方法を理解していません –

関連する問題