簡體   English   中英

從 tibble 創建列表列表

[英]Create list of lists from tibble

我正在嘗試做一些看起來很簡單的事情,但我無法弄清楚。 我有一個像這樣的小標題:

> df <- tibble::tribble(
  ~col_a, ~col_b,
  1,      "A",   
  2,      "B",   
  3,      "C",   
)
> df
# # A tibble: 3 x 2
# col_a col_b
# <dbl> <chr>
#   1     A    
#   2     B    
#   3     C 

我想把它變成一個看起來像這樣的列表

> str(res_list)
# List of 3
# $ :List of 2
# ..$ col_a: num 1
# ..$ col_b: chr "A"
# $ :List of 2
# ..$ col_a: num 2
# ..$ col_b: chr "B"
# $ :List of 2
# ..$ col_a: num 3
# ..$ col_b: chr "C"

我使用 base applydplyr::rowwise嘗試了很多東西,但沒有一個效果很好。 purrr::pmap的文檔中,我想我找到了答案:

f.   A function, formula, or vector (not necessarily atomic)...

If character vector, numeric vector, or list, it is converted to an extractor function. Character vectors index by name...

所以我想,這應該很好用: pmap(df, c("col_a", "col_b"))並且應該為每個元素(行)提取這些列並返回提取列表的列表。 但是當我運行時,我得到:

 Error in pluck(x, "col_a", "col_b", .default = NULL) : 
  argument "x" is missing, with no default 

我半理解這個錯誤,但我認為我正在關注文檔中的用法。 也許這只是 purrr 中的一個錯誤?

無論如何,歡迎對潛在的 purrr 錯誤進行評論,但實際上我只是想創建這個列表。 非常感謝任何幫助。

您可以使用group_split() (或基本split()如果您願意):

library(dplyr)
library(purrr)

df %>%
  group_split(row_number(), .keep = FALSE) %>%
  map(as.list)

其中str()給出:

List of 3
 $ :List of 2
  ..$ col_a: num 1
  ..$ col_b: chr "A"
 $ :List of 2
  ..$ col_a: num 2
  ..$ col_b: chr "B"
 $ :List of 2
  ..$ col_a: num 3
  ..$ col_b: chr "C"

或者:

lapply(split(df, 1:nrow(df)),
       as.list)

您可以使用asplit()

type.convert(lapply(asplit(df, 1), as.list), as.is = TRUE)

by()

`attributes<-`(by(df, 1:nrow(df), as.list), NULL)

str()都給出

List of 3
 $ :List of 2
  ..$ col_a: int 1
  ..$ col_b: chr "A"
 $ :List of 2
  ..$ col_a: int 2
  ..$ col_b: chr "B"
 $ :List of 2
  ..$ col_a: int 3
  ..$ col_b: chr "C"

我們可以使用pmap

library(purrr)
dflist <- df %>%
              pmap(~ list(...))
str(dflist)
#List of 3
# $ :List of 2
#  ..$ col_a: num 1
#  ..$ col_b: chr "A"
# $ :List of 2
#  ..$ col_a: num 2
#  ..$ col_b: chr "B"
# $ :List of 2
#  ..$ col_a: num 3
#  ..$ col_b: chr "C"

暫無
暫無

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

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