Q:

How to generate for loop in r to get different dataframe output with graphs?

This is the answer of the issue thanks to @Stewart Macdonald
I am using igraph package on large amount of data. I have a table with data per company and I need to generate a specific graph for each company. I need to generate tables with distance data for each company.
I need to generate a loop to generate my graphs for each of the companies but I am not really familiar with loops, in particular when it is not an iterative loop with number such as for i in (1:10)
# Packages : 
library(tidyverse)
library(igraph)
library(reshape2)

# Initial table:
dt1 <- tibble(V1=c("A","A","A","B","B","B"),
                  V2=c("B","C","D","A","D","A"),
                  Company=c("Comp_A","Comp_A","Comp_B","Comp_B","Comp_B","Comp_C"))

# List of variables:

comp_list <- dt1 %>%
  select(Company) %>%
  distinct
comp_list <- unique(dt1$Company)

# For loop:

Distance_data = data.frame()

for (this_company in comp_list)

{temp1 <- dt1 %>%
    filter(Company == this_company) %>%
    select(V1,V2)

  c <- graph_from_data_frame(temp1,directed = FALSE)
  c <- simplify(c,remove.multiple = TRUE)

  temp2 <- shortest.paths(c, v=V(c), to= V(c))
  temp2 <- melt(temp2)
  temp2 <- as_tibble(temp2)
  temp2$Var1 <- as.character(temp2$Var1)
  temp2$Var2 <- as.character(temp2$Var2)

  temp3 <- temp2 %>%
    mutate(id = paste(Var1,Var2)) %>%
    select(id,value,Var1,Var2) %>%
    mutate(Company = this_company) %>%
    distinct

Distance_data <- rbind(Distance_data,temp3)}

A:

I don't really understand what you're trying to achieve, but this might get you on the right track:
library(tidyverse)
library(igraph)
library(reshape2)

dt1 <- tibble(V1=c("A","A","A","B","B","B"),
              V2=c("B","C","D","A","D","A"),
                   Company=c("Comp_A","Comp_A","Comp_B","Comp_B","Comp_B","Comp_C"))

comp_list <- unique(dt1$Company)

Distance_data = data.frame()

for (this_company in comp_list) {
    temp1 <- dt1 %>% filter(Company == this_company) %>% select(V1,V2)

    print(temp1)

    c1 <- graph_from_data_frame(temp1,directed = FALSE)
    c1 <- simplify(c1, remove.multiple = TRUE)
    temp2 <- shortest.paths(c1, v=V(c1), to= V(c1))
    temp2 <- melt(temp2)
    temp2 <- as.tibble(temp2)
    temp2$Var1 <- as.character(temp2$Var1)
    temp2$Var2 <- as.character(temp2$Var2)

    #temp3 <- temp3 %>% mutate(id = paste(Var1, Var2, year)) %>% select(id,value,Var1,Var2,year) %>% distinct
    temp3 <- temp1

    Distance_data <- rbind(Distance_data, temp3)

}

print(Distance_data)

I don't know what the
temp3 <- temp3 %>%
   mutate(id = paste(Var1, Var2, year)) %>%
   select(id,value,Var1,Var2,year) %>%
   distinct

line is supposed to do, so I've commented it out to get the remaining code to run.

