create a nested list of different lengths of type igraph.vs with different values of type integer and convert it to a dataframe, if the list is empty put in nas in the new columns in r in r

main.r
# Load necessary libraries
library(igraph)
library(dplyr)
library(tidyr)

# Create a sample list of different lengths of type igraph.vs
vs_list <- list(
  vs1 = neighbors(graph = make_full_graph(5), order = 1),
  vs2 = neighbors(graph = make_full_graph(3), order = 1),
  vs3 = neighbors(graph = make_full_graph(4), order = 1)
)

# Find the maximum length in the list
max_length <- max(sapply(vs_list, length))

# Create a dataframe with NA values and add the list values to it
df <- data.frame(
  id = seq_along(vs_list),
  stringsAsFactors = FALSE
)

for (i in 1:max_length) {
  new_col <- sapply(vs_list, function(x) if (i <= length(x)) x[i] else NA)
  df[[paste0("col_", i)]] <- new_col
}

# If the list is empty, df will have only one column with id and rest will be NA
if (length(vs_list) == 0) {
  df <- data.frame(id = integer(0))
}

# Print the resulting dataframe
print(df)
883 chars
34 lines

gistlibby LogSnag