3

I am struggling to find a proper question for this, so I all ask it myself risking a duplicate

I have extracted the folder structure of my WD and I want to paste the names into a data frame for which each column represents one level of the folder structure.

Using strsplit I end up with a list of character vectors of which each element represents the name of the folder level. eg.

folders<-list(c("Main") , c("Main","Mid"), c("Main", "Mid", "Sub"))

What would be the easiest way to get a data frame out of this? In this case I would want three columns, but I have several more levels (probably down to six levels)

Expected result (NA could be ""):

data.frame(Level1=c("Main", "Main", "Main"), Level2=c(NA,"Mid", "Mid"), 
           Level3=c(NA,NA,"Sub"))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Max M
  • 806
  • 14
  • 29

1 Answers1

4

The easiest would be stri_list2matrix

library(stringi)
df <- as.data.frame(stri_list2matrix(folders, byrow = TRUE), stringsAsFactors=FALSE)
names(df) <- paste0("Level", seq_along(df))
df
#   Level1 Level2 Level3
#1   Main   <NA>   <NA>
#2   Main    Mid   <NA>
#3   Main    Mid    Sub

But, this can also be solved with base R

m1 <- max(lengths(folders))
d1 <- as.data.frame(do.call(rbind, lapply(folders, `length<-`, m1)), stringsAsFactors= FALSE)
names(d1) <- paste0("Level", seq_along(d1))
akrun
  • 874,273
  • 37
  • 540
  • 662