【问题标题】:Take out the elements of the most frequently occurring row of a matrix in R?取出R中矩阵中最常出现的行的元素?
【发布时间】:2017-12-26 20:17:00
【问题描述】:

在Base R中,是否可以取出(即只返回值)出现频率最高的元素以下矩阵中的行?

更新: @d.b 看到您的解决方案似乎从下面的矩阵 CI.test 中选择了错误的对。 CI 可以从您的解决方案中挑选,CI.test 是从中挑选最频繁行的元素的矩阵:

N = 60 ; df = N-1 ; d = 3

f <- function (ncp, alpha, q, df) {
  abs(suppressWarnings(pt(q = d*sqrt(N), df = df, ncp, lower.tail = FALSE)) - alpha)
  }

  a = mapply(c, as.list(20:30), as.list(-20:-30), SIMPLIFY = FALSE) # a list of paired values

 CI.test <- matrix(NA, length(a), 2)

 for(i in 1:length(a)){

CI.test[i,] = sapply(c(0.025, 0.975),
 function(x) optimize(f, interval = a[[i]], alpha = x, q = d*sqrt(N), df = df, tol = 1e-10)[[1]])

   }  

CI = CI.test[which.max(ave(1:nrow(CI.test), do.call(paste, data.frame(CI.test)), FUN = seq_along)), ]


  list(CI, CI.test)

【问题讨论】:

  • 你的预期输出是什么?

标签: r function matrix


【解决方案1】:

使用ave 计算配对的出现次数并提取出现次数最多的配对

m = matrix(c(-5.904236,  7.547438, 3.386315,  7.547438, -7.420706,
                                  7.547438, 3.386315,  7.547438), 4, 2)
m[which.max(ave(1:NROW(m), do.call(paste, data.frame(m)), FUN = seq_along)),]
#[1] 7.547438 7.547438

您可能需要对值进行四舍五入

CI.test[which.max(ave(1:NROW(CI.test), do.call(paste, round(data.frame(CI.test), 3)),
                                                                        FUN = seq_along)),]
#[1] 18.59838 27.83543

【讨论】:

  • @rnorouzian,没有round,实际值可能不完全相等。
  • 我明白了,但我不确定这里的一切是如何运作的,如果有机会请告诉我这是如何运作的,例如为什么需要paste
猜你喜欢
  • 1970-01-01
  • 2014-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多