简体   繁体   中英

using R apply to run a function on specific columns of a dataframe

I have this function which returns the edge weight (how to use the apply function in this case should not require any knowledge of the igraph library) of a link on a graph given a graph object igraph_obj (where the weight is stored after computation) for node1 and node2 (which are stored in a dataframe df):

dweight <- function(igraph_obj, node1, node2){
    return(E(igraph_obj)[node1 %->% node2]$weight)
}

I would like to apply this function on a dataframe which has this structure:

Node1 Node2 other_column1 other_column2 ...
a     b        1                2       ...
c     d        3                7       ...
...

I have read documentation and tutorials on the apply function and what I have tried so far has not worked to apply the function dweight onto each node1, node2, etc. If I had to write a loop to do it, it would do something like this: dweight(igraph_obj = g, df$Node1[i], df$Node2[i]) for each row i of df.

Hence, the apply function should look something like this:

apply(df, 1, dweight, igraph_obj=g) 

But then, dweight does not know which column of df to use as node1, node2. This does not work either:

apply(df, 1, dweight, igraph_obj=g, node1 = df$Node1, node2 = df$Node1)

Try:

  mapply(dweight, node1=df$Node1, node2=df$Node2, MoreArgs=list(igraph_obj=g))

That should work, but I cannot test it right now. If it doesn't, try:

  mapply(function(n1, n2) dweight(igraph_obj=g, n1, n2), df$Node1, df$Node2)

Alternatively, if you want to modify your function slightly:

dweight <- function(nodes, igraph_obj){
    node1 <- nodes$Node1
    node2 <- nodes$Node2
    return(E(igraph_obj)[node1 %->% node2]$weight)
}

And then you can use your apply function as you first tried:

 apply(df, 1, dweight, igraph_obj=g) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM