r - 根据最高 gamma 值创建一个包含文档主题值的向量
问题描述
我有一个包含 3 个变量 (document
和topic
)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)
解决方案
尽管其他解决方案工作正常,但我想提一下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))
推荐阅读
- ruby-on-rails - 附加普通 png 文件时出现 ActiveStorage::InvariableError?
- python - 当要求从文件导入时,Jupyter 使用过时版本的函数
- xcode - Cocoapods 无法在新的 m1 mac Big Sur Xcode 上运行
- java - 带有空指针异常的弹出对话框中的回收站视图
- c# - 忽略正则表达式验证中的新行
- sql - 匹配 Redshift 中逗号分隔字段中的值
- android - 你能从 OTM ROM 中提取 blob 吗?
- python - 使用 Pip 安装 Numpy/Pandas 的问题 - Wheel 问题
- biztalk - 在 BizTalk 中,为什么不能像“测试地图”一样“测试编排”
- angular - 我如何在我的服务中等待我的方法的结果?