[英]How do I aggregate results to get the most common number in each row of a dataset in R Studio
我正在做一些共識聚類,它返回一個名為“consensus_imouted”的集合,包含 3000 行,每行重復十次,集群編號(范圍為 1-6)。 我只想為每一行返回一列,每個列都有最常見的簇號。 例如,第一行是 3 3 3 3 3 3 3 3 6 3,所以我希望它是 3 等等。有什么幫助嗎?
您可以使用apply
function 如下:
sampledata <- matrix(sample(1:6,30000,replace = TRUE), ncol = 10, nrow = 3000)
sampledata <- data.frame(sampledata)
sampledata$mostCounts <- apply(sampledata,1, function(row0) {
as.numeric(names(which.max(table(row0))))
})
要獲得最頻繁的值,只需通過table
計算行中的值。 然后,使用which.max
選擇計數最高的值。 在表中,計數對應的值是表的名稱,因此使用names
來提取原始值。 現在,既然您知道它是數字,只需使用as.numeric
將字符轉換為數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.