Extracting outputs from lapply to a dataframe

前端 未结 4 1161
[愿得一人]
[愿得一人] 2020-12-30 02:25

I have some R code which performs some data extraction operation on all files in the current directory, using the following code:

files <- list.files(\".\         


        
相关标签:
4条回答
  • 2020-12-30 02:43

    One option might be to use the ldply function from the plyr package, which will stitch things back into a data frame for you.

    A trivial example of it's use:

    ldply(1:10,.fun = function(x){c(runif(1),"a")})
                        V1 V2
    1    0.406373084755614  a
    2    0.456838687881827  a
    3    0.681300171650946  a
    4    0.294320539338514  a
    5    0.811559669673443  a
    6    0.340881009353325  a
    7    0.134072444401681  a
    8  0.00850683846510947  a
    9    0.326008745934814  a
    10    0.90791508089751  a
    

    But note that if you're mixing variable types with c(), you probably will want to alter your function to return simply data.frame(name= name,value = value) instead of c(name,value). Otherwise everything will be coerced to character (as it is in my example above).

    0 讨论(0)
  • 2020-12-30 02:46
    inp <- list(c("amer", "14.5"), c("appl", "14.2"), .... # did not see need to copy all
    
    data.frame( first= sapply( inp, "[", 1), 
                second =as.numeric( sapply( inp, "[", 2) ) )
    
       first second
    1   amer   14.5
    2   appl   14.2
    3   brec   13.1
    4   camb   13.5
    5   camo   30.1
    6   cari   13.8
    snipped output
    
    0 讨论(0)
  • 2020-12-30 02:48

    Try this if results were your list:

    > as.data.frame(do.call(rbind, results))
    
         V1   V2
    1  amer 14.5
    2  appl 14.2
    3  brec 13.1
    4  camb 13.5
    ...
    
    0 讨论(0)
  • 2020-12-30 02:54

    Because and forNelton took the response I was in the process of giving and Joran took the only other reasonable response I could think of and since I'm supposed to be writing a paper here's a ridiculous answer:

    #I named your list LIST
    LIST2 <-  LIST[[1]]
    lapply(2:length(LIST), function(i) {LIST2 <<- rbind(LIST2, LIST[[i]])})
    data.frame(LIST2)
    
    0 讨论(0)
提交回复
热议问题