添加一列,其中包含具有最大频率的对象的值

Add a column with the value of the object with max frequency

我有这个矩阵:

mat=matrix(c(1,1,1,2,2,2,3,4,
             4,4,4,4,4,3,5,6,
             3,3,5,5,6,8,0,9,
             1,1,1,1,1,4,5,6),nrow=4,byrow=TRUE)
print(mat)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    2    2    2    3    4
[2,]    4    4    4    4    4    3    5    6
[3,]    3    3    5    5    6    8    0    9
[4,]    1    1    1    1    1    4    5    6

和一个子集,其中包含我要应用函数的行的索引:

subset=c(2,4)

我想在矩阵 "mat" 中添加一个新列,其中仅包含我指定的子集,该行中具有最大频率的对象的值。

在这种情况下:

编辑: 感谢答案中的代码! 现在我应该用其他值替换 NA 值: 我有另一个矩阵:

mat2=matrix(c(24,1,3,2, 4,4,4,4, 3,2,2,5, 1,3,5,1),nrow=4,byrow=TRUE)

     [,1] [,2] [,3] [,4]
[1,]   24    1    3    2
[2,]    4    4    4    4
[3,]    3    2    2    5
[4,]    1    3    5    1

和子集:

subset=c(1,3)

我想用具有最大值的行的值的列名替换矩阵的 NA(第一个子集中的剩余行)。

在这种情况下,第一行为“1”,第三行为“4”。

您正在寻找模式。不幸的是,R 不提供内置模式功能。但是自己写一个也不难:

## create mode function
modeValue <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

## add new column with NA
smat <- cbind(mat, NA)

## calculate mode for subset
smat[subset, ncol(smat)] <- apply(smat[subset, , drop=FALSE], 1, modeValue)
smat
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
# [1,]    1    1    1    2    2    2    3    4   NA
# [2,]    4    4    4    4    4    3    5    6    4
# [3,]    3    3    5    5    6    8    0    9   NA
# [4,]    1    1    1    1    1    4    5    6    1

这是一个可以使用的函数。它计算所有行的此类值(模式),然后在需要的地方替换缺失值:

myFunc <- function(x, myRows) {

  myModes <- apply(mat, 1, FUN=function(i) {
                temp<- table(i)
                as.numeric(names(temp)[which.max(temp)])
             })
  myModes[setdiff(seq.int(nrow(x)), myRows)] <- NA
  myModes
}

例如,这个returns

myFunc(mat, c(2,4))
[1] NA  4 NA  1

要将其添加到您的矩阵中,只需使用 cbind:

cbind(mat, myFunc(mat, c(2,4)))
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    1    1    1    2    2    2    3    4   NA
[2,]    4    4    4    4    4    3    5    6    4
[3,]    3    3    5    5    6    8    0    9   NA
[4,]    1    1    1    1    1    4    5    6    1