简体   繁体   中英

Create tibble from list elements in R

So I have this list of lists and inside each list I have elements that are vectors of equal lengths and a single value in one element. I want to create a tibble of the vectors and store the tibble in the list of lists.

> neighbours
$p1
$p1$course_names
 [1] "X1"  "X2"  "X3"

$p1$course_capacities
 [1] 1 1 1 

$p1[[2]]
[1] 4.123106

$p2
$p2$course_names
 [1] "X1"  "X2"  "X3"

$p2$course_capacities
 [1] 1 1 1 

$p2[[2]]
[1] 4.123106

Final output should look like this:

> neighbours
[[1]]
[[1]][[1]]
# A tibble: 10 x 4
   course_names course_capacities
   <chr>                    <dbl>
 1 X1                        1.00
 2 X2                        1.00
 3 X3                        1.00

[[1]][[2]]
[1] 4.123106

[[2]]
[[1]][[1]]
# A tibble: 10 x 4
   course_names course_capacities
   <chr>                    <dbl>
 1 X1                        1.00
 2 X2                        1.00
 3 X3                        1.00

[[2]][[2]]
[1] 4.123106

I guess I'd prefer a tidyverse solution since I am looking for tibbles. Of course, I am happy to consider any approach.

its not a great structure but there are two ways. First off I have tried to recreate your initial list:

neighbours <- list(p1 = list(
                         list(course_names = c("X1","X2","X3"),
                              course_capabilities = c(1,1,1)),
                         4.123106
                         ),
               p2 = list(
                         list(course_names = c("X1","X2","X3"),
                                 course_capabilities = c(1,1,1)),
                         4.123106
                         )
)

then either use lapply() or purrr::map()

neighbours %>% purrr::map(~list(as_tibble(.[[1]]),.[[2]]))

or

lapply(neighbours, function(p){
  list(as_tibble(p[[1]]), 
       p[[2]])
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM