library(flowWorkspace)
library(graph)
dataDir <- system.file("extdata",package="flowWorkspaceData")
gs <- load_gs(list.files(dataDir, pattern = "gs_manual",full = TRUE))
plot(gs)

#get tree as graphNEL object
g <- flowWorkspace:::.getGraph(gs[[1]]) 

#get node datra
node.data <- graph::nodeData(g)

#get node id for CD4 and CD8 
cd4.ind <- which(sapply(node.data, function(i)i[["label"]] == "CD4"))
cd8.ind <- which(sapply(node.data, function(i)i[["label"]] == "CD8"))
cd4.id <- names(cd4.ind)
cd8.id <- names(cd8.ind)

#swap nodeData(including label) between two them
tmp.cd4 <- node.data[[cd4.id]]
tmp.cd8 <- node.data[[cd8.id]]
for(i in names(node.data[[cd4.id]])){
  nodeData(g, cd4.id, i) <- tmp.cd8[[i]] 
  nodeData(g, cd8.id, i) <- tmp.cd4[[i]]
}

#update their children by swapping edges 
egs <- edges(g) 

cd4.children.ind <- which(sapply(names(egs), function(eg){
          
          cd4.id %in% inEdges(eg,g)[[1]]
        }))
cd4.children.id  <- names(cd4.children.ind)

cd8.children.ind <- which(sapply(names(egs), function(eg){
          
          cd8.id %in% inEdges(eg,g)[[1]]
        }))
cd8.children.id  <- names(cd8.children.ind)


g <- removeEdge(cd4.id, cd4.children.id, g)
g <- removeEdge(cd8.id, cd8.children.id, g)

for(i in cd8.children.id)
  g <- addEdge(cd4.id, i, g)
for(i in cd4.children.id)
  g <- addEdge(cd8.id, i, g)

#plot the tree
flowWorkspace:::.plotGatingTree(g)