R/transform_network.R

# Transforming the output for network in D3.js
transform_network = function (connections = NULL, aggregated_nodes = NULL ) {

  # ---- Nodes ----
  nodes = aggregated_nodes %>%
    dplyr::group_by(nodes) %>%
    dplyr::summarise(size=n()) %>%
    dplyr::ungroup() %>%
    dplyr::mutate(name = row_number() - 1 ) %>%
    dplyr::select(name, nodes, size)

  # ---- Links ----
  # Adding the names of the nodes to simplified nodes
  aggregated_nodes = merge(aggregated_nodes, nodes) %>%
    dplyr::select(id, name)

  # Adding the names of the links and simplifying them
  links = merge(
    merge(connections,
          aggregated_nodes %>%
            dplyr::rename(row = id, source = name)
          ),
    aggregated_nodes %>%
      dplyr::rename(col = id, target = name)
  ) %>%
    dplyr::mutate(min = pmin(source, target), max = pmax(source, target)) %>%
    dplyr::select(-source, -target) %>%
    dplyr::rename(source = min, target = max) %>%
    dplyr::group_by(source, target) %>%
    dplyr::summarise(size = n()) %>%
    dplyr::ungroup()

  # Output
  return( list(
    nodes = as.data.frame(nodes),
    links = as.data.frame(links)
  ))
}
danielalcaide/mclean documentation built on May 28, 2019, 7:51 p.m.