首页 > 解决方案 > 根据最高 gamma 值创建一个包含文档主题值的向量

问题描述

我有一个包含 3 个变量 (documenttopic)gamma的数据框

document    topic   gamma
1            1      0.932581726
1            2      0.015250915
1            3      0.009929329
2            1      0.032864538
2            2      0.012939786
2            3      0.13281681

我想创建一个向量,其中包含基于最高 gamma 值的文档的主题值。对于哪个主题 gamma 值高,文档属于该主题。

我尝试了一些代码,但不确定这是获取它的正确方法。

a2<-function(x){
  i=1
while(i< 110)
  for(j in 1:7)
    x= max(ap_documents$gamma)
  return(j)
  }
a3<-sapply(ap_documents,a2)

标签: rdataframe

解决方案


尽管其他解决方案工作正常,但我想提一下top_n-function in dplyr,它是为解决类似任务而构建的:

library(dplyr)

my_df %>% 
  group_by(document) %>% 
  top_n(1, topic)

# A tibble: 2 x 3
# Groups:   document [2]
#   document topic   gamma
#      <int> <int>   <dbl>
# 1        1     3 0.00993
# 2        2     3 0.133

另一个简单的基础 R 解决方案也是:

my_df <- my_df[order(my_df$topic, decreasing = TRUE), ]
my_df[!duplicated(my_df$document), ]

#   document topic       gamma
# 3        1     3 0.009929329
# 6        2     3 0.132816810

数据

my_df <- structure(list(document = c(1L, 1L, 1L, 2L, 2L, 2L), 
                        topic = c(1L, 2L, 3L, 1L, 2L, 3L), 
                        gamma = c(0.932581726, 0.015250915, 0.009929329, 
                                  0.032864538, 0.012939786, 0.13281681)), 
                   class = "data.frame", row.names = c(NA, -6L))

推荐阅读