如何创建特定的数据框

时间:2018-03-17 10:55:27

标签: r dataframe output

A_F <- lapply(shortest_paths(graph, from='A', mode ='all', weights = E(graph)$Gewicht, output='epath')$epath,
  function(x) { x$label })

对数据框有疑问。输入此代码后,我有output

是否可以将此数据保存为类似的数据框? dataframe

1 个答案:

答案 0 :(得分:0)

好像您想将列表转换为数据框。请尝试以下方法:

### creating a list similar to your example
mylist <- list("x1", c("x2", "x6"), c("x1", "x3"), "x2", c("x2", "x6", "x7"))

### determining the length of the longest string in the list 
maxlength <- max(sapply(mylist, length))

### creating a function to set the lengths of all elments in the list to maxlength
myfct <- function(x){
  if(length(x) == maxlength){return(x)}
  if(length(x) != maxlength){return(c(x, rep(NA, maxlength-length(x))))}
}

### here the final output
> t(sapply(mylist, FUN = myfct))
     [,1] [,2] [,3]
[1,] "x1" NA   NA  
[2,] "x2" "x6" NA  
[3,] "x1" "x3" NA  
[4,] "x2" NA   NA  
[5,] "x2" "x6" "x7"