-1

For example, I have the following lists:

A   B
"a" c("1","2")
"b" c("3","4","5")

where A is a list of strings and B is a list of tuples of strings. and I want to the the following list:

C
c("a","1")
c("a","2")
c("b","3")
c("b","4")
c("b","5")

which is a list with one element in A and one element in the corresponding tuple in B.

rconradin
  • 346
  • 4
  • 10
leonfrank
  • 201
  • 2
  • 4
  • 7
  • 1
    Your example is unclear ([use `dput`](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#5963610)), but if you have a list column, you can use `tidyr::unnest`, e.g. `library(tidyverse); df <- data_frame(A = c('a', 'b'), B = list(1:2, 3:5)); df %>% unnest()` – alistaire May 29 '17 at 22:56

2 Answers2

1

There surely are other ways to do this, but here's a way to solve this using tidyverse tools. Hope it helps.

EDIT: I updated the answer after you explained the data was structured differently than I originally thought.

library(dplyr)
library(tidyr)
library(purrr)

A <- list("a", "b")
B <- list(c("1","2"), c("3","4","5"))

C <- tibble(A = as_vector(A), B) %>% 
  tidyr::unnest(B) %>% 
  mutate(C = map2(A, B, ~c(.x, .y))) %>% 
  .[["C"]]

C

#> [[1]]
#> [1] "a" "1"
#> 
#> [[2]]
#> [1] "a" "2"
#> 
#> [[3]]
#> [1] "b" "3"
#> 
#> [[4]]
#> [1] "b" "4"
#> 
#> [[5]]
#> [1] "b" "5"
austensen
  • 2,857
  • 13
  • 24
  • Sorry, I mean that A and B are 2 separate lists. My idea is to map the vectors in list B to bind the elements in list A. So how can I do that? – leonfrank May 29 '17 at 23:43
  • It would be helpful to include the actual code to create the objects you're working with, the way they are at the top of my answer. – austensen May 30 '17 at 01:09
  • @leonfrank I updated the answer to reflect this different data structure – austensen May 30 '17 at 02:14
0

We can use base R

d1 <- stack(setNames(B, unlist(A)))[2:1]
d1$ind <- as.character(d1$ind)
split(unlist(d1, use.names = FALSE), 1:nrow(d1))  
#$`1`
#[1] "a" "1"

#$`2`
#[1] "a" "2"

#$`3`
#[1] "b" "3"

#$`4`
#[1] "b" "4"

#$`5`
#[1] "b" "5"
akrun
  • 874,273
  • 37
  • 540
  • 662