2016-11-08 96 views
2

我想知道有可能使用導入的數據表來創建類似樹形圖(UTF-8編碼的)類似這樣的:如何創建中的R樹圖

col0 col1    col2  col3 col4 
name <NA>    <NA>  <NA>  NA 
name dog, cat, bird dog  Canis  3 
name dog, cat, bird cat  Feline 3 
name dog, cat, bird bird  Avis  4 

我嘗試使用此代碼示例:

library(rpart) 
raw = subset(dataset, select=c("col1","col2","col3")) 
formula = col1 ~ col3 
fit = rpart(formula, method="class", data=raw) 

但我收到錯誤,如:「矩陣必須匹配的行數」或在其他情況下,這個彈出:「錯誤:意外‘>’「>」

最後我」米試圖得到更多的圖表以下像下面的圖片:enter image description here

回答

1

你可以使用包製圖器給你這樣一個形象:

enter image description here

dataset <- data.frame(
    col0="name", 
    col1=c(NA, "dog, cat, bird", "dog, cat, bird", "dog, cat, bird"), 
    col2=c(NA, "dog", "cat", "bird"), 
    col3=c(NA, "Canis", "Feline", "Avis"), 
    col4=c(NA, 3, 3, 4), 
    stringsAsFactors=FALSE) 

# remove rows with missing values 
sub <- dataset[!is.na(dataset$col1), ] 

uniquenodes <- unique(c(sub$col1, sub$col3)) 

library(DiagrammeR) 

nodes <- create_nodes(nodes=seq(uniquenodes), type="number", label=uniquenodes) 

edges <- create_edges(from=match(sub$col1, uniquenodes), 
    to=match(sub$col3, uniquenodes), rel="related") 

g <- create_graph(nodes_df=nodes, edges_df=edges) 

render_graph(g) 
1

隨着IGRAPH:

df <- df[df$col1 != '<NA>',] 
species <- union(df$col1, df$col3) 
df <- df[c('col1', 'col3')] 
names(df) <- c('from', 'to') 
g <- graph.data.frame(df, directed = TRUE, vertices = species) 
plot(g,vertex.size=95, vertex.label.dist=0.5, vertex.color="green", 
    edge.arrow.size=0.5, layout=layout.reingold.tilford(g, root='dog,cat,bird')) 

enter image description here