我有以下数据:
Newspaper Month Year Date Topic1 Topic2 Topic3 Topic4 Topic5
1 Scotsman December 2005 December 2005 0.013749700 0.000127470 0.38575261 0.000127470 0.070778523
2 Scotsman December 2005 December 2005 0.000165017 0.000165017 0.05219433 0.004611941 0.000165017
3 Scotsman December 2005 December 2005 0.000356507 0.024344932 0.01135670 0.000356507 0.000356507
4 Scotsman December 2005 December 2005 0.000185186 0.000185186 0.10796924 0.044639345 0.106613401
5 Scotsman December 2005 December 2005 0.065869506 0.009775978 0.09610254 0.017584819 0.000103681
6 Scotsman December 2005 December 2005 0.000153257 0.000153257 0.11443001 0.000153257 0.046316677
我想创建一个与TopicN
对应的单独变量,其百分比更高。
在第一篇文章(行)的情况下,它会是3.任何想法?
答案 0 :(得分:8)
您可以在主题列上使用max.col()
。如果df
是数据,请尝试
max.col(df[grepl("^Topic", names(df))])
# [1] 3 3 2 3 3 3
因此,要添加新列MaxPct
,我们可以
df$MaxPct <- max.col(df[grepl("^Topic", names(df))])
答案 1 :(得分:4)
我们可以将apply
与which.max
unname(apply(df[grepl("^Topic", names(df))], 1, which.max))
#[1] 3 3 2 3 3 3