如何使用 purrr 从两个元素的列表中提取元素?

how to extract elements from lists of two elements using purrr?

我正在使用 quanteda 的朴素贝叶斯模型 (textmodel_nb) 来做一些文本-class化。

模型的输出之一是一个列表,其中包含每个 class 的概率。也就是说,如果 nb 是我的模型,我会看到

 > str(nb$PcGw)
 num [1:2, 1:462] 0.9446 0.0554 0.9259 0.0741 0.2932 ...
 - attr(*, "dimnames")=List of 2
  ..$ classes : chr [1:2] "FALSE" "TRUE"
  ..$ features: chr [1:462] "hello" "john" "jan" "index" ..

并打印列表会给出类似

的内容
 nb$PcGw
       features
classes         ny        john
  FALSE 0.94457605 0.92594799
  TRUE  0.05542395 0.07405201

我想用 purrr 来提取这些信息并想出一个 data_frame

variable    P_TRUE     P_FALSE
'ny'        0.05542395 0.94457605
'john'      0.07405201 0.92594799

但是,我做不到。有人可以帮我吗?

这是一个使用 quanteda 自己的示例的工作示例:

txt <- c(d1 = "Chinese Beijing Chinese",
         d2 = "Chinese Chinese Shanghai",
         d3 = "Chinese Macao",
         d4 = "Tokyo Japan Chinese",
         d5 = "Chinese Chinese Chinese Tokyo Japan")
trainingset <- dfm(txt, tolower = FALSE)
trainingclass <- factor(c("Y", "Y", "Y", "N", NA), ordered = TRUE)

## replicate IIR p261 prediction for test set (document 5)
nb_test <- textmodel_nb(trainingset, trainingclass)

str(nb_test$PcGw)

 num [1:2, 1:6] 0.659 0.341 0.562 0.438 0.562 ...
 - attr(*, "dimnames")=List of 2
  ..$ classes : chr [1:2] "Y" "N"
  ..$ features: chr [1:6] "Chinese" "Beijing" "Shanghai" "Macao"

谢谢!!

如果我们需要转置并格式化列,使用 %>%,转置矩阵,转换为 data.frame ,添加一列行名 (rownames_to_column) 和必要时重命名

library(tidyverse)
nb_test$PwGc %>% 
     t %>% 
     as.data.frame %>% 
     rownames_to_column('variable') %>% 
     rename_at(2:3, ~ paste0("P_", c(TRUE, FALSE)))

根据与OP的沟通,如果我们需要在%>%中嵌套一些语句,用{}

包裹起来
nb_test$PcGw %>% 
      t %>%
      as.data.frame() %>% 
      {as_tibble(rownames_to_column(., 'variable'))}

或者直接使用

nb_test$PcGw %>%
    t %>% 
    as.data.frame() %>% 
    rownames_to_column(., 'variable') %>% 
    as_tibble()