Combine two lists in a dataframe in R

后端 未结 6 2204
青春惊慌失措
青春惊慌失措 2021-02-07 08:46

I have two lists with different structure:

listA <- list(c(\"a\",\"b\",\"c\"), c(\"d\",\"e\"))
listB <- list(0.05, 0.5)

listA
[[1]]
[1] \"a\" \"b\" \"c\"
         


        
相关标签:
6条回答
  • 2021-02-07 09:23

    Here is another way:

    do.call(rbind,
            lapply(1:length(listA),
                   function(i)
                     data.frame(A=unlist(listA[i]),
                                B=unlist(listB[i]))))
    
    0 讨论(0)
  • 2021-02-07 09:25

    I'd prefer this:

    do.call(rbind,
            Map(function(...) setNames(cbind.data.frame(...), 
                                       c("A", "B")), 
                listA, listB))
    #  A    B
    #1 a 0.05
    #2 b 0.05
    #3 c 0.05
    #4 d 0.50
    #5 e 0.50
    
    0 讨论(0)
  • 2021-02-07 09:33

    This is another option:

    do.call(rbind, Map(data.frame, A=listA, B=listB))
    
    #   A    B
    # 1 a 0.05
    # 2 b 0.05
    # 3 c 0.05
    # 4 d 0.50
    # 5 e 0.50
    
    0 讨论(0)
  • 2021-02-07 09:39

    Another way without using do.call:

    cbind(data.frame(listA), data.frame(listB))
    
    0 讨论(0)
  • 2021-02-07 09:45

    If looking for a tidyverse solution, here is the analogue to the accepted answer. Using the dfr suffix to the map function family enables a very simple solution which should also be faster than do.call("rbind").

    library(tidyverse)
    listA <- list(c("a","b","c"), c("d","e"))
    listB <- list(0.05, 0.5)
    
    map2_dfr(listA, listB, ~ tibble(A = .x, B = .y))
    #> # A tibble: 5 x 2
    #>   A         B
    #>   <chr> <dbl>
    #> 1 a      0.05
    #> 2 b      0.05
    #> 3 c      0.05
    #> 4 d      0.5 
    #> 5 e      0.5
    

    Created on 2019-02-12 by the reprex package (v0.2.1)

    0 讨论(0)
  • 2021-02-07 09:48

    Maybe there is a more elegant way that keeps the class numeric of list2's elements... But this one works as well

    df <- do.call(rbind,mapply(cbind, listA, listB))
    df <- as.data.frame(df, stringsAsFactors = FALSE)
    df[,2] <- as.numeric(df[,2])
    

    EDIT Way better is Matthew Plourde's solution using Map aka mapply(data.frame, A=listA, B=listB, SIMPLIFY = FALSE)

    0 讨论(0)
提交回复
热议问题