This is a follow-up question from : Creating treechart from tabbed text in R
I am using following function:
treechart = function(){
library(psych)
fields <- max(count.fields(textConnection(readClipboard()), sep = "\t"))
dat = read.table(text = readClipboard(), sep="\t",col.names = paste0("V", sequence(fields)), header=FALSE, fill=TRUE, strip.white=TRUE, stringsAsFactors=FALSE, na.strings="")
library(zoo)
library(igraph)
# To prepare the data
# carry forward the last value in columns if lower level (col to the right)
# is non-missing
dat[1] <- na.locf(dat[1], na.rm=FALSE)
for(i in ncol(dat):2) {
dat[[i-1]] <- ifelse(!is.na(dat[[i]]), na.locf(dat[[i-1]], na.rm=F), dat[[i-1]])
}
# get edges for graph
edges <- rbind(na.omit(dat[1:2]),
do.call('rbind',
lapply(1:(ncol(dat)-2), function(i)
na.omit(setNames(dat[(1+i):(2+i)],
names(dat[1:2])))))
)
# create graph
g <- graph.data.frame(edges)
# Plot graph
E(g)$curved <- 0
plot.igraph(g, vertex.size=0, edge.arrow.size=0 , layout=-layout.reingold.tilford(g)[,2:1])
}
I am using following example data (separated by tabs in text editor or from spreadsheet) which I select and copy with control-C:
AAA
BBB
CCC
DDD
III
JJJ
LLL
EEE
KKK
FFF
GGG
Then on running the command 'treechart()' I get following chart:
Here DDD and EEE are coming higher than BBB, CCC. Similarly, JJJ is coming before III. How can I correct the function treechart() for this order to be always correct? Thanks for your help.