代码之家  ›  专栏  ›  技术社区  ›  ℕʘʘḆḽḘ

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

  •  1
  • ℕʘʘḆḽḘ  · 技术社区  · 8 年前

    我正在使用 quanteda 的朴素贝叶斯模型( textmodel_nb )进行一些文本分类。

    模型的输出之一是一个列表,其中包含每个类的概率。也就是说,如果 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"
    

    谢谢

    1 回复  |  直到 8 年前
        1
  •  1
  •   akrun    8 年前

    如果需要转置并格式化列,请使用 %>% ,转置矩阵,转换为 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()