R/kegg_link.R

Defines functions kegg_parse_link kegg_link_dbs kegg_linkage_graph kegg_link

# superfunction

kegg_link <- function(source, target) {

    url <- sprintf('http://rest.kegg.jp/link/%s/%s', target, source)

    resp <- httr::GET(url)

    if (.kegg_check_response(resp)) {
        return(kegg_parse_link(resp))
        return(resp)
    }

    stop(httr::http_status(resp)$message)
}

kegg_linkage_graph <- function(el) {

    #el <- kegg_make_db_el(query)

    g <- igraph::graph_from_edgelist(el, directed = F) |>
        igraph::simplify()

    return(g)

}

kegg_link_dbs <- function(g) {
    # make graph
    #g <- kegg_linkage_graph(query, F)
    # find all simple paths
    p <- lapply(all_shortest_paths(g, V(g)[[1]])$res, names)[-1]
    # all datasets
    l <- names(V(g))
    # loop through the paths and connect datasets
    l <- lapply(p, \(pth) {

        if(any(mapply(kegg_is_conv, pth))) {
            kegg_conv(pth[1], pth[2])
        } else {
            kegg_link(pth[1], pth[2]) |>
                kegg_parse_link(cnames = pth)
        }

        # frg <- zoo::rollapply(pth, 2, by = 1, c)
        # frg <- split(frg, row(frg))
        #
        # res_lst02 <- lapply(
        #     frg,
        #     \(datum) {
        #         resp <- kegg_link(datum[[1]], datum[[2]])
        #         kegg_parse_link(resp, datum)
        #     }
        # )
        #
        # res02 <- res_lst02[[1]]
        #
        # for(datum in res_lst02[-1]) {
        #     res02 <- dplyr::left_join(res02, datum, by = colnames(datum)[[1]])
        # }
        #
        # return(res02)

    })


    res <- l[[1]]

    for(datum in l[-1]) {
        res <- dplyr::inner_join(res, datum, by = colnames(datum)[[1]])
    }

    return(res)

}

kegg_parse_link <- function(response, cnames = NULL) {
    txt <- httr::content(response, encoding = 'utf-8')
    res <- read.delim(text = txt, header = FALSE, sep = '\t', strip.white = TRUE)
    if(length(cnames) == ncol(res)) {
        colnames(res) <- cnames
    }
    return(res)
}

# when linking, not all genes are returned, but those which annotated at first linkage
utubun/keggr documentation built on Jan. 29, 2022, 5:08 a.m.