簡體   English   中英

在 R 中將列表合並為一個列表

[英]Combine lists into a single list in R

我有單獨的列表,例如:

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

我怎樣才能將所有列表合並到一個列表中,這樣:

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

我想保存在 dataframe 中,這樣

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

dput的輸入:

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

當我使用 cbind 時,它返回:

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

而不是我想要的

這里明顯的解決方案是簡單地unlist列出您的列表:

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!!"

代表 package (v2.0.1) 於 2022 年 7 月 31 日創建

我們可以使用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!!   

我們可以用

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!!"   
  • 數據
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!!" )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM