Home > database >  Combine lists into a single list in R
Combine lists into a single list in R

Time:08-01

I have seperate lists such that:

1. $text = "I love this product"
2. $text = "Amazing service and care given, will visit once again"
3. $text = "Love this product!!" 

How could i merge all lists into one list such that:

$text = ["I love this product", "Amazing service and care given, will visit once again", "Love this product!!"]

I would like to save in in a dataframe such that

Product Reviews 
A       ["I love this product", "Amazing service and care given, will visit once again", "Love this product!!"]
B       ["I ......."]

dput of the list:

list(list(text="I love this product"),
     list(text="Amazing service and care given, will visit once again"), 
     list(text="Love this product!!"))

When I used cbind, it returns:

Reviews
"I love this product"
"Amazing service and care given, will visit once again"
"Love this product!!"

instead of what i wanted

CodePudding user response:

The obvious solution here is to simply unlist your list:

list(text = unlist(mylist, use.names = FALSE))
#> $text
#> [1] "I love this product"                                  
#> [2] "Amazing service and care given, will visit once again"
#> [3] "Love this product!!"

Created on 2022-07-31 by the reprex package (v2.0.1)

CodePudding user response:

We could use bind_rows:

library(dplyr)

my_list %>% 
  bind_rows() %>% 
  mutate(Product = LETTERS[1:n()], .before=1)
  Product text                                                 
  <chr>   <chr>                                                
1 A       I love this product                                  
2 B       Amazing service and care given, will visit once again
3 C       Love this product!!   

CodePudding user response:

We can use

c(l1,l2,l3) |> sapply(paste0) |>
            unname() |> list(text = _) 
  • output
$text
[1] "I love this product"                                  
[2] "Amazing service and care given, will visit once again"
[3] "Love this product!!"   
  • data
l1 <- list(text = "I love this product" )
l2 <- list(text = "Amazing service and care given, will visit once again" )
l3 <- list(text = "Love this product!!" )
  •  Tags:  
  • r
  • Related