Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用purrr从两个元素的列表中提取元素?_R_Dplyr_Purrr - Fatal编程技术网

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

如何使用purrr从两个元素的列表中提取元素?,r,dplyr,purrr,R,Dplyr,Purrr,我正在使用quanteda的朴素贝叶斯模型(textmodel\u 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" ..$ feat

我正在使用
quanteda
的朴素贝叶斯模型(
textmodel\u 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
我想用
purr
来提取这些信息,并提出一个
data\u框架

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"

txt如果我们需要获得转置并格式化列,使用
%%>%%
,转置矩阵,转换为
数据帧
,添加一列行名(
行名到列
),并在必要时重命名

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() 

为什么不转置nb_测试$PcGw?类似于
data.frame(t(nb_test$PwGc))
如果您在管道中需要它
nb_test$PwGc%%t%%>%as.data.frame%%rownames_to_column('variable')%%>%rename_at(2:3,~paste0(“P_u”),c(TRUE,FALSE))
@NOOBIE我想您需要将它放在
{}
中我的意思是
nb PcGw%%>%t%%>%as.data.frame()%%>{(rownames_to_column(,'variable'))}
由于对
%>%
BTW中的参数进行了计算,您的
map_chr
在矩阵的各个元素而不是列中循环,即
nb$PcGw%>%map(,.x)