intStdu
intStdu

Reputation: 291

How do i add rows to a dataframe with a function in R

I want to create a dataframe from several community detection metric outputs using the package 'igraph'. However, when I made my function to do so, I only get the output dataframe returned, the original dataframe is not altered and still empty. How can i achieve this?

First, I made an empty dataframe with 3 columns, 1 character column and two numerical columns. I want to append the result of each algorithm to this dataframe. I tried this with the self-made 'maker' function using dplyr.

df_com_det_1 <- data.frame(algorithm=character(),groups=numeric(0)
                          ,mod=numeric(0),stringsAsFactors=FALSE)

maker <- function(dataframe, methodused){
  dataframe %>%
    summarise(algorithm = methodused$algorithm,
              groups = length(unique(methodused$membership)),
              mod = methodused$modularity) %>%
    bind_rows(dataframe, .)
}

maker(df_com_det_1, label_propagation_unweighted)

I hope to see no output in the console, but I do hope to see an altered df_com_det_1 dataframe with the following row added (which is now only returned in the console):

> maker(df_com_det_1, label_propagation_unweighted)
          algorithm groups       mod
1 label propagation      3 0.4534836

How could i achieve this?

Upvotes: 1

Views: 461

Answers (1)

iod
iod

Reputation: 7592

When you call your function you're not assigning the result to anything. Try

df_com_det_1<-maker(df_com_det_1,label_propagation_unweighted)

When you call a function with your dataframe a copy of that dataframe is created in a new environment internal to that function, and all the changes made to that dataframe are not reflected in the external environment.

There's a way to make changes in the global environment from within a function (using <<-), but it's really really not recommended. A much better solution is to do what I suggested above, and simply assign the result of your function back into the dataframe.

Upvotes: 2

Related Questions